├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── deploy-docs.yml │ └── zizmor.yml ├── .gitignore ├── LICENSE ├── README.md ├── docs ├── developer.md ├── general-usage.md ├── images │ └── logo.png ├── index.md └── requirements-docs.txt ├── mkdocs.yml ├── pyproject.toml ├── requirements-dev.txt ├── requirements.txt ├── setup.py ├── technical ├── __init__.py ├── bouncyhouse.py ├── candles.py ├── consensus │ ├── __init__.py │ ├── consensus.py │ ├── movingaverage.py │ ├── oscillator.py │ └── summary.py ├── indicator_helpers.py ├── indicators │ ├── __init__.py │ ├── cycle_indicators.py │ ├── indicators.py │ ├── momentum.py │ ├── overlap_studies.py │ ├── price_transform.py │ ├── volatility.py │ └── volume_indicators.py ├── pivots_points.py ├── qtpylib.py ├── trendline.py ├── util.py └── vendor │ ├── __init__.py │ └── qtpylib │ ├── __init__.py │ └── indicators.py └── tests ├── __init__.py ├── __snapshots__ └── test_indicators_generic.ambr ├── conftest.py ├── exchange └── __init__.py ├── image ├── __init__.py └── test_get_coin_in_image.py ├── test_indicator_helpers.py ├── test_indicators.py ├── test_indicators_generic.py ├── test_util.py └── testdata └── UNITTEST_BTC-1m.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | groups: 9 | types: 10 | patterns: 11 | - "types-*" 12 | pytest: 13 | patterns: 14 | - "pytest*" 15 | 16 | - package-ecosystem: "github-actions" 17 | directory: "/" 18 | schedule: 19 | interval: "weekly" 20 | open-pull-requests-limit: 10 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Technical CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - ci/* 8 | tags: 9 | release: 10 | types: [published] 11 | pull_request: 12 | schedule: 13 | - cron: '0 5 * * 4' 14 | 15 | 16 | concurrency: 17 | group: "${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}" 18 | cancel-in-progress: true 19 | 20 | permissions: 21 | contents: read 22 | 23 | jobs: 24 | test: 25 | 26 | runs-on: ${{ matrix.os }} 27 | strategy: 28 | matrix: 29 | os: [ "ubuntu-22.04", "ubuntu-24.04", "macos-13", "macos-14", "macos-15" ] 30 | python-version: ["3.10", "3.11", "3.12", "3.13"] 31 | exclude: 32 | - os: macos-13 33 | python-version: "3.13" 34 | 35 | steps: 36 | - uses: actions/checkout@v4 37 | with: 38 | persist-credentials: false 39 | 40 | - name: Set up Python 41 | uses: actions/setup-python@v5.1.1 42 | with: 43 | python-version: ${{ matrix.python-version }} 44 | 45 | - name: Cache_dependencies 46 | uses: actions/cache@v4 47 | id: cache 48 | with: 49 | path: ~/dependencies/ 50 | key: ${{ matrix.os }}-dependencies 51 | 52 | - name: pip cache (linux) 53 | uses: actions/cache@v4 54 | if: startsWith(matrix.os, 'ubuntu') 55 | with: 56 | path: ~/.cache/pip 57 | key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip 58 | 59 | - name: pip cache (macOS) 60 | uses: actions/cache@v4 61 | if: startsWith(matrix.os, 'macOS') 62 | with: 63 | path: ~/Library/Caches/pip 64 | key: test-${{ matrix.os }}-${{ matrix.python-version }}-pip 65 | 66 | - name: TA binary *nix 67 | if: steps.cache.outputs.cache-hit != 'true' 68 | run: | 69 | wget https://github.com/freqtrade/freqtrade/raw/develop/build_helpers/ta-lib-0.4.0-src.tar.gz 70 | tar zxvf ta-lib-0.4.0-src.tar.gz 71 | cd ta-lib 72 | ./configure --prefix ${HOME}/dependencies/ 73 | make 74 | which sudo && sudo make install || make bigip_software_install 75 | cd .. 76 | rm -rf ta-lib/ 77 | 78 | - name: Installation - *nix 79 | run: | 80 | python -m pip install --upgrade pip 81 | export LD_LIBRARY_PATH=${HOME}/dependencies/lib:$LD_LIBRARY_PATH 82 | export TA_LIBRARY_PATH=${HOME}/dependencies/lib 83 | export TA_INCLUDE_PATH=${HOME}/dependencies/include 84 | pip install -r requirements-dev.txt 85 | pip install -e . 86 | 87 | - name: Tests 88 | run: | 89 | pytest --random-order --cov=technical --cov-config=.coveragerc 90 | 91 | - name: Run Ruff 92 | run: | 93 | ruff check --output-format=github . 94 | 95 | - name: Run Ruff format check 96 | run: | 97 | ruff format --check 98 | 99 | - name: Run Codespell 100 | run: | 101 | codespell 102 | 103 | - name: Sort imports (isort) 104 | run: | 105 | isort --check . 106 | 107 | - name: Discord notification 108 | uses: rjstone/discord-webhook-notify@1399c1b2d57cc05894d506d2cfdc33c5f012b993 #v1.1.1 109 | if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) 110 | with: 111 | severity: error 112 | details: Technical CI failed on ${{ matrix.os }} 113 | webhookUrl: ${{ secrets.DISCORD_WEBHOOK }} 114 | 115 | 116 | test_windows: 117 | 118 | runs-on: ${{ matrix.os }} 119 | strategy: 120 | matrix: 121 | os: [ windows-latest ] 122 | python-version: ["3.10", "3.11", "3.12", "3.13"] 123 | 124 | steps: 125 | - uses: actions/checkout@v4 126 | with: 127 | persist-credentials: false 128 | 129 | - name: Set up Python 130 | uses: actions/setup-python@v5.1.1 131 | with: 132 | python-version: ${{ matrix.python-version }} 133 | 134 | - name: Pip cache (Windows) 135 | uses: actions/cache@v4 136 | if: startsWith(runner.os, 'Windows') 137 | with: 138 | path: ~\AppData\Local\pip\Cache 139 | key: ${{ matrix.os }}-${{ matrix.python-version }}-pip 140 | 141 | - uses: actions/checkout@v4 142 | with: 143 | persist-credentials: false 144 | repository: freqtrade/freqtrade 145 | path: './freqtrade_tmp' 146 | 147 | - name: Installation (uses freqtrade dependencies) 148 | run: | 149 | cp -r ./freqtrade_tmp/build_helpers . 150 | 151 | ./build_helpers/install_windows.ps1 152 | 153 | - name: Tests 154 | run: | 155 | pytest --random-order --cov=technical --cov-config=.coveragerc tests 156 | 157 | - name: Run Ruff 158 | run: | 159 | ruff check --output-format=github technical tests 160 | 161 | - name: Discord notification 162 | uses: rjstone/discord-webhook-notify@1399c1b2d57cc05894d506d2cfdc33c5f012b993 #v1.1.1 163 | if: failure() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) 164 | with: 165 | severity: error 166 | details: Technical CI failed on ${{ matrix.os }} 167 | webhookUrl: ${{ secrets.DISCORD_WEBHOOK }} 168 | 169 | # Notify on discord only once - when CI completes (and after deploy) in case it's successfull 170 | notify-complete: 171 | needs: [ test, test_windows ] 172 | runs-on: ubuntu-latest 173 | # Discord notification can't handle schedule events 174 | if: (github.event_name != 'schedule') 175 | steps: 176 | - name: Check user permission 177 | id: check 178 | uses: scherermichael-oss/action-has-permission@136e061bfe093832d87f090dd768e14e27a740d3 # 1.0.6 179 | with: 180 | required-permission: write 181 | env: 182 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 183 | 184 | - name: Discord notification 185 | uses: rjstone/discord-webhook-notify@1399c1b2d57cc05894d506d2cfdc33c5f012b993 #v1.1.1 186 | if: always() && steps.check.outputs.has-permission && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) 187 | with: 188 | severity: info 189 | details: Technical CI 190 | webhookUrl: ${{ secrets.DISCORD_WEBHOOK }} 191 | 192 | build: 193 | needs: [ test, test_windows ] 194 | runs-on: ubuntu-22.04 195 | steps: 196 | - uses: actions/checkout@v4 197 | with: 198 | persist-credentials: false 199 | 200 | - name: Set up Python 201 | uses: actions/setup-python@v5.1.1 202 | with: 203 | python-version: 3.11 204 | 205 | - name: Extract branch name 206 | id: extract-branch 207 | run: | 208 | echo "GITHUB_REF='${GITHUB_REF}'" 209 | echo "branch=${GITHUB_REF##*/}" >> "$GITHUB_OUTPUT" 210 | 211 | - name: Build distribution 212 | run: | 213 | pip install -U build 214 | python -m build --sdist --wheel 215 | 216 | - name: Upload artifacts 📦 217 | uses: actions/upload-artifact@v4 218 | with: 219 | name: technical 220 | path: | 221 | dist 222 | retention-days: 10 223 | 224 | deploy-test-pypi: 225 | if: (github.event_name == 'release') && github.repository == 'freqtrade/technical' 226 | needs: [ build ] 227 | runs-on: ubuntu-22.04 228 | environment: 229 | name: pypi-test 230 | url: https://test.pypi.org/p/technical 231 | permissions: 232 | id-token: write 233 | 234 | steps: 235 | 236 | - name: Download artifact 📦 237 | uses: actions/download-artifact@v4 238 | with: 239 | name: technical 240 | path: dist 241 | merge-multiple: true 242 | 243 | - name: Publish to PyPI (Test) 244 | uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4 245 | if: (github.event_name == 'release') 246 | with: 247 | repository-url: https://test.pypi.org/legacy/ 248 | 249 | deploy-pypi: 250 | if: (github.event_name == 'release') && github.repository == 'freqtrade/technical' 251 | needs: [ build ] 252 | runs-on: ubuntu-22.04 253 | environment: 254 | name: pypi 255 | url: https://pypi.org/p/technical 256 | permissions: 257 | id-token: write 258 | 259 | steps: 260 | 261 | - name: Download artifact 📦 262 | uses: actions/download-artifact@v4 263 | with: 264 | name: technical 265 | path: dist 266 | merge-multiple: true 267 | 268 | - name: Publish to PyPI 269 | uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4 270 | 271 | - name: Discord notification 272 | uses: rjstone/discord-webhook-notify@1399c1b2d57cc05894d506d2cfdc33c5f012b993 #v1.1.1 273 | if: always() && ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false) 274 | with: 275 | severity: info 276 | details: Technical CI Deploy 277 | webhookUrl: ${{ secrets.DISCORD_WEBHOOK }} 278 | -------------------------------------------------------------------------------- /.github/workflows/deploy-docs.yml: -------------------------------------------------------------------------------- 1 | name: Build Documentation 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | release: 8 | types: [published] 9 | 10 | 11 | # disable permissions for all of the available permissions 12 | permissions: {} 13 | 14 | 15 | jobs: 16 | build-docs: 17 | permissions: 18 | contents: write # for mike to push 19 | name: Deploy Docs through mike 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v4 23 | with: 24 | persist-credentials: true 25 | 26 | - name: Set up Python 27 | uses: actions/setup-python@v5 28 | with: 29 | python-version: '3.12' 30 | 31 | - name: Install dependencies 32 | run: | 33 | python -m pip install --upgrade pip 34 | pip install -r docs/requirements-docs.txt 35 | 36 | - name: Fetch gh-pages branch 37 | run: | 38 | git fetch origin gh-pages --depth=1 39 | 40 | - name: Configure Git user 41 | run: | 42 | git config --local user.email "github-actions[bot]@users.noreply.github.com" 43 | git config --local user.name "github-actions[bot]" 44 | 45 | - name: Build and push Mike 46 | if: ${{ github.event_name == 'push' }} 47 | run: | 48 | mike deploy ${REF_NAME} latest --push --update-aliases 49 | env: 50 | REF_NAME: ${{ github.ref_name }} 51 | 52 | - name: Build and push Mike - Release 53 | if: ${{ github.event_name == 'release' }} 54 | run: | 55 | mike deploy ${REF_NAME} stable --push --update-aliases 56 | env: 57 | REF_NAME: ${{ github.ref_name }} 58 | 59 | - name: Show mike versions 60 | run: | 61 | mike list 62 | 63 | -------------------------------------------------------------------------------- /.github/workflows/zizmor.yml: -------------------------------------------------------------------------------- 1 | name: GitHub Actions Security Analysis with zizmor 🌈 2 | 3 | on: 4 | push: 5 | branches: 6 | - "main" 7 | - "ci/*" 8 | pull_request: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | zizmor: 14 | name: zizmor latest via PyPI 15 | runs-on: ubuntu-latest 16 | permissions: 17 | security-events: write 18 | contents: read # only needed for private repos 19 | actions: read # only needed for private repos 20 | steps: 21 | - name: Checkout repository 22 | uses: actions/checkout@v4 23 | with: 24 | persist-credentials: false 25 | 26 | - name: Install the latest version of uv 27 | uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 28 | 29 | - name: Run zizmor 🌈 30 | run: uvx zizmor --format=sarif . > results.sarif 31 | env: 32 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 33 | 34 | - name: Upload SARIF file 35 | uses: github/codeql-action/upload-sarif@v3 36 | with: 37 | sarif_file: results.sarif 38 | category: zizmor 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env 88 | env/ 89 | venv/ 90 | ENV/ 91 | env.bak/ 92 | venv.bak/ 93 | 94 | # Spyder project settings 95 | .spyderproject 96 | .spyproject 97 | 98 | # Rope project settings 99 | .ropeproject 100 | 101 | # mkdocs documentation 102 | /site 103 | 104 | # mypy 105 | .mypy_cache/ 106 | 107 | # IDE Specific 108 | .vscode 109 | .idea 110 | 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Technical 2 | 3 | ![Technical CI](https://github.com/freqtrade/technical/actions/workflows/ci.yml/badge.svg) 4 | ![Documentation CI](https://github.com/freqtrade/technical/actions/workflows/deploy-docs.yml/badge.svg) 5 | [![PyPI](https://img.shields.io/pypi/v/technical)](https://pypi.org/project/technical/) 6 | [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) 7 | 8 | Technical is a companion project for Freqtrade. 9 | It includes technical indicators, as well as helpful utilities (e.g. timeframe resampling) aimed to assist in strategy development for Freqtrade. 10 | 11 | ## What does it do for you 12 | 13 | Technical provides easy to use indicators, collected from all over github, as well as custom methods. 14 | Over time we plan to provide a simple API wrapper around TA-Lib, PyTi and others, as we find them. So you have one place, to find 100s of indicators. 15 | 16 | ### Custom indicators 17 | 18 | * Consensus - an indicator which is based on a consensus model, across several indicators 19 | you can easily customize these. It is based on the [TradingView](https://www.tradingview.com/symbols/BTCUSD/technicals/) 20 | buy/sell graph. - MovingAverage Consensus - Oscillator Consensus - Summary Consensus 21 | * [vfi](https://www.tradingview.com/script/MhlDpfdS-Volume-Flow-Indicator-LazyBear/) - a modified version of On-Balance Volume (OBV) created by Markos Katsanos that gives better interpretation of current market trend. 22 | * [mmar](https://www.tradingview.com/script/1JKqmEKy-Madrid-Moving-Average-Ribbon/) - an indicator that uses multiple MAs of different length to categorize the market trend into 4 different categories 23 | * [madrid_sqz](https://www.tradingview.com/script/9bUUSzM3-Madrid-Trend-Squeeze/) - an indicator that uses multiple MAs to categorize the market trend into 6 different categories and to spot a squeeze 24 | * [stc](https://www.investopedia.com/articles/forex/10/schaff-trend-cycle-indicator.asp) 25 | * [ichimoku cloud](http://stockcharts.com/school/doku.php?id=chart_school:trading_strategies:ichimoku_cloud) 26 | * [volume weighted moving average](https://trendspider.com/learning-center/what-is-the-volume-weighted-moving-average-vwma/) - a variation of the Simple Moving Average (SMA) that taking into account both price and volume 27 | * [laguerre](https://www.tradingview.com/script/iUl3zTql-Ehlers-Laguerre-Relative-Strength-Index-CC/) - an indicator developed by John Ehlers as a way to minimize both the noise and lag of the regular RSI 28 | * [vpci](https://www.tradingview.com/script/lmTqKOsa-Indicator-Volume-Price-Confirmation-Indicator-VPCI/) 29 | * [trendlines](https://en.wikipedia.org/wiki/Trend_line_(technical_analysis)) - 2 different algorithms to calculate trendlines 30 | * [fibonacci_retracements](https://www.investopedia.com/terms/f/fibonacciretracement.asp) - an indicator showing the fibonacci level which each candle exceeds 31 | * [pivots points](https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/) 32 | * [TKE Indicator](https://www.tradingview.com/script/Pcbvo0zG/) - Arithmetical mean of 7 oscilators 33 | * [Volume Weighted MACD](https://www.tradingview.com/script/wVe6AfGA) - Volume Weighted MACD indicator 34 | * [RMI](https://www.marketvolume.com/technicalanalysis/relativemomentumindex.asp) - Relative Momentum indicator 35 | * [VIDYA](https://www.tradingview.com/script/64ynXU2e/) - Variable Index Dynamic Average 36 | * [MADR](https://www.tradingview.com/script/25KCgL9H/) - Moving Average Deviation Rate 37 | * [SSL](https://www.tradingview.com/script/xzIoaIJC-SSL-channel/) - SSL Channel 38 | * [PMAX](https://www.tradingview.com/script/sU9molfV/) - PMAX indicator 39 | * [ALMA](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.alma) - Arnaud Legoux Moving Average 40 | 41 | ### Utilities 42 | 43 | * resample - easily resample your dataframe to a larger interval 44 | * merge - merge your resampled dataframe into your original dataframe, so you can build triggers on more than 1 interval! 45 | 46 | ### Wrapped Indicators 47 | 48 | The following indicators are available and have been 'wrapped' to be used on a dataframe with the standard open/close/high/low/volume columns: 49 | 50 | * [chaikin_money_flow](https://www.tradingview.com/wiki/Chaikin_Money_Flow_(CMF)) - Chaikin Money Flow, requires dataframe and period 51 | * [accumulation_distribution](https://www.investopedia.com/terms/a/accumulationdistribution.asp) - requires a dataframe 52 | * osc - requires a dataframe and the periods 53 | * [atr](https://www.investopedia.com/terms/a/atr.asp) - dataframe, period, field 54 | * [atr_percent](https://www.investopedia.com/terms/a/atr.asp) - dataframe, period, field 55 | * [bollinger_bands](https://www.investopedia.com/terms/b/bollingerbands.asp) - dataframe, period, stdv, field, prefix 56 | * [cmo](https://www.investopedia.com/terms/c/chandemomentumoscillator.asp) - dataframe, period, field 57 | * [cci](https://www.investopedia.com/terms/c/commoditychannelindex.asp) - dataframe, period 58 | * [williams percent](https://www.investopedia.com/terms/w/williamsr.asp) 59 | * momentum oscillator 60 | * [hull moving average](https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/hull-moving-average) 61 | * ultimate oscillator 62 | * [sma](https://www.investopedia.com/terms/s/sma.asp) 63 | * [ema](https://www.investopedia.com/terms/e/ema.asp) 64 | * [tema](https://www.investopedia.com/terms/t/triple-exponential-moving-average.asp) 65 | 66 | We will try to add more and more wrappers as we get to it, but please be patient or help out with PR's! It's super easy, but also super boring work. 67 | 68 | ### Usage 69 | 70 | to use the library, please install it with pip 71 | 72 | ```bash 73 | pip install technical 74 | ``` 75 | 76 | To get the latest version, install directly from github: 77 | 78 | ```bash 79 | pip install git+https://github.com/freqtrade/technical 80 | ``` 81 | 82 | and then import the required packages 83 | 84 | ```python 85 | from technical.indicators import accumulation_distribution, ... 86 | from technical.util import resample_to_interval, resampled_merge 87 | 88 | # Assuming 1h dataframe -resampling to 4h: 89 | dataframe_long = resample_to_interval(dataframe, 240) # 240 = 4 * 60 = 4h 90 | 91 | dataframe_long['rsi'] = ta.RSI(dataframe_long) 92 | # Combine the 2 dataframes 93 | dataframe = resampled_merge(dataframe, dataframe_long, fill_na=True) 94 | 95 | """ 96 | The resulting dataframe will have 5 resampled columns in addition to the regular columns, 97 | following the template resample__. 98 | So in the above example: 99 | ['resample_240_open', 'resample_240_high', 'resample_240_low','resample_240_close', 'resample_240_rsi'] 100 | """ 101 | 102 | ``` 103 | 104 | ### Contributions 105 | 106 | We will happily add your custom indicators to this repo! 107 | Just clone this repository and implement your favorite indicator to use with Freqtrade and create a Pull Request. 108 | 109 | Please run both `ruff check .` and `ruff format .` before creating a PR to avoid unnecessary failures in CI. 110 | 111 | Have fun! 112 | -------------------------------------------------------------------------------- /docs/developer.md: -------------------------------------------------------------------------------- 1 | # Developer documentation 2 | 3 | This page is intended for developers of the `technical` library, people who want to contribute to the `technical` codebase or documentation, or people who want to understand the source code of the application they're running. 4 | 5 | All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. We [track issues](https://github.com/freqtrade/technical/issues) on [GitHub](https://github.com/freqtrade/technical). 6 | For generic questions, please use the [discord server](https://discord.gg/p7nuUNVfP7), where you can ask questions. 7 | 8 | ## Releases 9 | 10 | Bump the `__version__` naming in `technical/__init__.py` and create a new release on github with a matching tag. 11 | 12 | !!! Note 13 | Version numbers must follow allowed versions from PEP0440 to avoid failures pushing to pypi. 14 | 15 | ### Pypi 16 | 17 | Pypi releases happen automatically on a new release through github actions. 18 | -------------------------------------------------------------------------------- /docs/general-usage.md: -------------------------------------------------------------------------------- 1 | # General Usage 2 | 3 | After installation, technical can be imported and used in your code. 4 | 5 | We recommend to import freqtrade.indicators as ftt to avoid conflicts with other libraries, and to help determining where indicator calculations came from. 6 | 7 | ```python 8 | import technical.indicators as ftt 9 | 10 | # The indicator calculations can now be used as follows: 11 | 12 | dataframe['cmf'] = ftt.chaikin_money_flow(dataframe) 13 | ``` 14 | 15 | ## Indicator functions 16 | 17 | All built in indicators are designed to work with a pandas DataFrame as provided by freqtrade, containing the standard columns: open, high, low, close and volume. 18 | This dataframe should be provided as the first argument to the indicator function. 19 | Depending on the indicator, additional parameters may be required. 20 | 21 | ### Return type 22 | 23 | Depending on the indicator, the return type may be a pandas Series, a tuple of pandas Series, or a pandas DataFrame. 24 | 25 | ## Resample to interval 26 | 27 | The helper methods `resample_to_interval` and `resampled_merge` are used to resample a dataframe to a higher timeframe and merge the resampled dataframe back into the original dataframe. 28 | This is an alternative approach to using informative pairs and reduces the amount of data needed from the exchange (you don't need to download 4h candles in the below example). 29 | 30 | ```python 31 | from pandas import DataFrame 32 | from technical.util import resample_to_interval, resampled_merge 33 | import technical.indicators as ftt 34 | 35 | timeframe = '1h' 36 | 37 | def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 38 | 39 | # Resampling to 4h: 40 | dataframe_long = resample_to_interval(dataframe, 240) # 240 = 4 * 60 = 4h 41 | 42 | dataframe_long['cmf'] = ftt.chaikin_money_flow(dataframe_long) 43 | # Combine the 2 dataframes 44 | dataframe = resampled_merge(dataframe, dataframe_long, fill_na=True) 45 | 46 | 47 | # The resulting dataframe will have 5 resampled columns in addition to the regular columns, 48 | # following the template resample__. 49 | # So in the above example, the column names would be: 50 | # ['resample_240_open', 'resample_240_high', 'resample_240_low','resample_240_close', 'resample_240_cmf'] 51 | 52 | return dataframe 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/docs/images/logo.png -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Technical 2 | 3 | ![Technical CI](https://github.com/freqtrade/technical/actions/workflows/ci.yml/badge.svg) 4 | ![Documentation CI](https://github.com/freqtrade/technical/actions/workflows/deploy-docs.yml/badge.svg) 5 | [![PyPI](https://img.shields.io/pypi/v/technical)](https://pypi.org/project/technical/) 6 | [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) 7 | 8 | Technical is a companion project for Freqtrade. 9 | It includes technical indicators, as well as helpful utilities (e.g. timeframe resampling) aimed to assist in strategy development for Freqtrade. 10 | 11 | ## What does it do for you 12 | 13 | Technical provides easy to use indicators, collected from all over github, as well as custom methods. 14 | Over time we plan to provide a simple API wrapper around TA-Lib, PyTi and others, as we find them. So you have one place, to find 100s of indicators. 15 | 16 | ### Custom indicators 17 | 18 | * Consensus - an indicator which is based on a consensus model, across several indicators 19 | you can easily customize these. It is based on the [TradingView](https://www.tradingview.com/symbols/BTCUSD/technicals/) 20 | buy/sell graph. - MovingAverage Consensus - Oscillator Consensus - Summary Consensus 21 | * [vfi](https://www.tradingview.com/script/MhlDpfdS-Volume-Flow-Indicator-LazyBear/) - a modified version of On-Balance Volume (OBV) created by Markos Katsanos that gives better interpretation of current market trend. 22 | * [mmar](https://www.tradingview.com/script/1JKqmEKy-Madrid-Moving-Average-Ribbon/) - an indicator that uses multiple MAs of different length to categorize the market trend into 4 different categories 23 | * [madrid_sqz](https://www.tradingview.com/script/9bUUSzM3-Madrid-Trend-Squeeze/) - an indicator that uses multiple MAs to categorize the market trend into 6 different categories and to spot a squeeze 24 | * [stc](https://www.investopedia.com/articles/forex/10/schaff-trend-cycle-indicator.asp) 25 | * [ichimoku cloud](http://stockcharts.com/school/doku.php?id=chart_school:trading_strategies:ichimoku_cloud) 26 | * [volume weighted moving average](https://trendspider.com/learning-center/what-is-the-volume-weighted-moving-average-vwma/) - a variation of the Simple Moving Average (SMA) that taking into account both price and volume 27 | * [laguerre](https://www.tradingview.com/script/iUl3zTql-Ehlers-Laguerre-Relative-Strength-Index-CC/) - an indicator developed by John Ehlers as a way to minimize both the noise and lag of the regular RSI 28 | * [vpci](https://www.tradingview.com/script/lmTqKOsa-Indicator-Volume-Price-Confirmation-Indicator-VPCI/) 29 | * [trendlines](https://en.wikipedia.org/wiki/Trend_line_(technical_analysis)) - 2 different algorithms to calculate trendlines 30 | * [fibonacci_retracements](https://www.investopedia.com/terms/f/fibonacciretracement.asp) - an indicator showing the fibonacci level which each candle exceeds 31 | * [pivots points](https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/) 32 | * [TKE Indicator](https://www.tradingview.com/script/Pcbvo0zG/) - Arithmetical mean of 7 oscilators 33 | * [Volume Weighted MACD](https://www.tradingview.com/script/wVe6AfGA) - Volume Weighted MACD indicator 34 | * [RMI](https://www.marketvolume.com/technicalanalysis/relativemomentumindex.asp) - Relative Momentum indicator 35 | * [VIDYA](https://www.tradingview.com/script/64ynXU2e/) - Variable Index Dynamic Average 36 | * [MADR](https://www.tradingview.com/script/25KCgL9H/) - Moving Average Deviation Rate 37 | * [SSL](https://www.tradingview.com/script/xzIoaIJC-SSL-channel/) - SSL Channel 38 | * [PMAX](https://www.tradingview.com/script/sU9molfV/) - PMAX indicator 39 | * [ALMA](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.alma) - Arnaud Legoux Moving Average 40 | 41 | ### Utilities 42 | 43 | * resample - easily resample your dataframe to a larger interval 44 | * merge - merge your resampled dataframe into your original dataframe, so you can build triggers on more than 1 interval! 45 | 46 | ### Wrapped Indicators 47 | 48 | The following indicators are available and have been 'wrapped' to be used on a dataframe with the standard open/close/high/low/volume columns: 49 | 50 | * [chaikin_money_flow](https://www.tradingview.com/wiki/Chaikin_Money_Flow_(CMF)) - Chaikin Money Flow, requires dataframe and period 51 | * [accumulation_distribution](https://www.investopedia.com/terms/a/accumulationdistribution.asp) - requires a dataframe 52 | * osc - requires a dataframe and the periods 53 | * [atr](https://www.investopedia.com/terms/a/atr.asp) - dataframe, period, field 54 | * [atr_percent](https://www.investopedia.com/terms/a/atr.asp) - dataframe, period, field 55 | * [bollinger_bands](https://www.investopedia.com/terms/b/bollingerbands.asp) - dataframe, period, stdv, field, prefix 56 | * [cmo](https://www.investopedia.com/terms/c/chandemomentumoscillator.asp) - dataframe, period, field 57 | * [cci](https://www.investopedia.com/terms/c/commoditychannelindex.asp) - dataframe, period 58 | * williams percent 59 | * momentum oscillator 60 | * hull moving average 61 | * ultimate oscillator 62 | * sma 63 | * ema 64 | * tema 65 | 66 | We will try to add more and more wrappers as we get to it, but please be patient or help out with PR's! It's super easy, but also super boring work. 67 | 68 | ### Usage 69 | 70 | to use the library, please install it with pip 71 | 72 | ```bash 73 | pip install technical 74 | ``` 75 | 76 | To get the latest version, install directly from github: 77 | 78 | ```bash 79 | pip install git+https://github.com/freqtrade/technical 80 | ``` 81 | 82 | and then import the required packages 83 | 84 | ```python 85 | from technical.indicators import accumulation_distribution, ... 86 | from technical.util import resample_to_interval, resampled_merge 87 | 88 | # Assuming 1h dataframe -resampling to 4h: 89 | dataframe_long = resample_to_interval(dataframe, 240) # 240 = 4 * 60 = 4h 90 | 91 | dataframe_long['rsi'] = ta.RSI(dataframe_long) 92 | # Combine the 2 dataframes 93 | dataframe = resampled_merge(dataframe, dataframe_long, fill_na=True) 94 | 95 | """ 96 | The resulting dataframe will have 5 resampled columns in addition to the regular columns, 97 | following the template resample__. 98 | So in the above example: 99 | ['resample_240_open', 'resample_240_high', 'resample_240_low','resample_240_close', 'resample_240_rsi'] 100 | """ 101 | 102 | ``` 103 | 104 | ### Contributions 105 | 106 | We will happily add your custom indicators to this repo! 107 | Just clone this repository and implement your favorite indicator to use with Freqtrade and create a Pull Request. 108 | 109 | Have fun! 110 | -------------------------------------------------------------------------------- /docs/requirements-docs.txt: -------------------------------------------------------------------------------- 1 | markdown==3.8 2 | mkdocs==1.6.1 3 | mkdocs-material==9.6.14 4 | mdx_truly_sane_lists==1.3 5 | pymdown-extensions==10.15 6 | jinja2==3.1.6 7 | mike==2.1.3 8 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Technical 2 | site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://technical.freqtrade.io/'] 3 | site_description: Technical is a companion library for Freqtrade, providing a collection of technical analysis indicators and utilities. 4 | repo_url: https://github.com/freqtrade/technical 5 | edit_uri: edit/main/docs/ 6 | use_directory_urls: True 7 | nav: 8 | - Home: index.md 9 | - General usage: general-usage.md 10 | - Contributors Guide: developer.md 11 | 12 | theme: 13 | name: material 14 | logo: "images/logo.png" 15 | favicon: "images/logo.png" 16 | # custom_dir: "docs/overrides" 17 | features: 18 | - content.code.annotate 19 | - search.share 20 | - content.code.copy 21 | - navigation.top 22 | - navigation.footer 23 | palette: 24 | - scheme: default 25 | primary: "blue grey" 26 | accent: "tear" 27 | toggle: 28 | icon: material/toggle-switch-off-outline 29 | name: Switch to dark mode 30 | - scheme: slate 31 | primary: "blue grey" 32 | accent: "tear" 33 | toggle: 34 | icon: material/toggle-switch 35 | name: Switch to light mode 36 | markdown_extensions: 37 | - attr_list 38 | - admonition 39 | - footnotes 40 | - codehilite: 41 | guess_lang: false 42 | - toc: 43 | permalink: true 44 | - pymdownx.arithmatex: 45 | generic: true 46 | - pymdownx.details 47 | - pymdownx.inlinehilite 48 | - pymdownx.magiclink 49 | - pymdownx.pathconverter 50 | - pymdownx.smartsymbols 51 | - pymdownx.snippets: 52 | base_path: docs 53 | check_paths: true 54 | - pymdownx.superfences 55 | - pymdownx.tabbed: 56 | alternate_style: true 57 | - pymdownx.tasklist: 58 | custom_checkbox: true 59 | - pymdownx.tilde 60 | - mdx_truly_sane_lists 61 | 62 | extra: 63 | version: 64 | provider: mike 65 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools >= 46.4.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "technical" 7 | dynamic = ["version"] 8 | authors = [ 9 | {name = "Freqtrade Team"}, 10 | {name = "Freqtrade Team", email = "freqtrade@protonmail.com"}, 11 | ] 12 | description = "Technical Indicators for Financial Analysis" 13 | readme = "README.md" 14 | requires-python = ">=3.10" 15 | license = {text = "GPLv3"} 16 | classifiers = [ 17 | "Programming Language :: Python :: 3", 18 | "Programming Language :: Python :: 3.10", 19 | "Programming Language :: Python :: 3.11", 20 | "Programming Language :: Python :: 3.12", 21 | "Programming Language :: Python :: 3.13", 22 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 23 | "Topic :: Office/Business :: Financial :: Investment", 24 | "Intended Audience :: Science/Research", 25 | ] 26 | 27 | dependencies = [ 28 | "TA-lib", 29 | "pandas", 30 | ] 31 | [project.optional-dependencies] 32 | tests = [ 33 | "pytest", 34 | "pytest-cov", 35 | "pytest-mock", 36 | "pytest-random-order" 37 | ] 38 | 39 | 40 | [project.urls] 41 | Homepage = "https://github.com/freqtrade/technical" 42 | "Bug Tracker" = "https://github.com/freqtrade/technical/issues" 43 | 44 | [tool.setuptools] 45 | include-package-data = false 46 | zip-safe = false 47 | 48 | [tool.setuptools.packages.find] 49 | where = [ "." ] 50 | exclude = [ 51 | "tests*", 52 | ] 53 | 54 | [tool.setuptools.dynamic] 55 | version = {attr = "technical.__version__"} 56 | 57 | [tool.black] 58 | line-length = 100 59 | exclude = ''' 60 | ( 61 | /( 62 | \.eggs # exclude a few common directories in the 63 | | \.git # root of the project 64 | | \.hg 65 | | \.mypy_cache 66 | | \.tox 67 | | \.venv 68 | | _build 69 | | buck-out 70 | | build 71 | | dist 72 | )/ 73 | # Exclude vendor directory 74 | | vendor 75 | ) 76 | ''' 77 | 78 | [tool.isort] 79 | line_length = 100 80 | 81 | 82 | [tool.ruff] 83 | line-length = 100 84 | 85 | [tool.ruff.lint] 86 | extend-select = [ 87 | "TID", # flake8-tidy-imports 88 | # "EXE", # flake8-executable 89 | "YTT", # flake8-2020 90 | # "DTZ", # flake8-datetimez 91 | # "RSE", # flake8-raise 92 | # "TCH", # flake8-type-checking 93 | # "PTH", # flake8-use-pathlib 94 | "NPY", # numpy 95 | ] 96 | 97 | 98 | [tool.flake8] 99 | max-line-length = 100 100 | extend-ignore = "E203" 101 | 102 | 103 | [tool.codespell] 104 | ignore-words-list = "vave" 105 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | 3 | pytest==8.4.0 4 | pytest-cov==6.1.1 5 | pytest-mock==3.14.1 6 | pytest-random-order==1.1.1 7 | # Pytest snapshots 8 | syrupy==4.9.1 9 | 10 | ruff==0.11.13 11 | isort==6.0.1 12 | codespell==2.4.1 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | TA-Lib==0.5.5 2 | pandas==2.3.0 3 | numpy==2.2.6 4 | # matplotlib 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /technical/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.5.1" 2 | -------------------------------------------------------------------------------- /technical/bouncyhouse.py: -------------------------------------------------------------------------------- 1 | """ 2 | helper file for calculating touches and bounces of or under supports and resistances 3 | """ 4 | 5 | import numpy as np 6 | from pandas import DataFrame 7 | 8 | 9 | def _touch(high, low, level, open, close): 10 | """ 11 | was the given level touched 12 | :param high: 13 | :param low: 14 | :param level: 15 | :return: 16 | """ 17 | if high > level and low < level: 18 | if open >= close: 19 | return -1 20 | else: 21 | return 1 22 | else: 23 | return 0 24 | 25 | 26 | def _bounce(open, close, level, previous_touch): 27 | """ 28 | did we bounce above the given level 29 | :param open: 30 | :param close: 31 | :param level: 32 | :param previous_touch 33 | :return: 34 | """ 35 | 36 | if previous_touch == 1 and open > level and close > level: 37 | return 1 38 | elif previous_touch == 1 and open < level and close < level: 39 | return -1 40 | else: 41 | return 0 42 | 43 | 44 | def bounce(dataframe: DataFrame, level): 45 | """ 46 | 47 | :param dataframe: 48 | :param level: 49 | :return: 50 | 1 if it bounces up 51 | 0 if no bounce 52 | -1 if it bounces below 53 | """ 54 | 55 | from scipy.ndimage.interpolation import shift 56 | 57 | open = dataframe["open"] 58 | close = dataframe["close"] 59 | touch = shift(touches(dataframe, level), 1, cval=np.nan) 60 | 61 | return np.vectorize(_bounce)(open, close, level, touch) 62 | 63 | 64 | def touches(dataframe: DataFrame, level): 65 | """ 66 | :param dataframe: our incoming dataframe 67 | :param level: where do we want to calculate the touches 68 | returns all the touches of the dataframe on the given level 69 | 70 | :returns 71 | 1 if it touches and closes above 72 | 0 if it doesn't touch 73 | -1 if it touches and closes below 74 | """ 75 | 76 | open = dataframe["open"] 77 | close = dataframe["close"] 78 | high = dataframe["high"] 79 | low = dataframe["low"] 80 | 81 | return np.vectorize(_touch)(high, low, level, open, close) 82 | -------------------------------------------------------------------------------- /technical/candles.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy.ndimage import shift 4 | 5 | 6 | def heikinashi(bars): 7 | """ 8 | Heikin Ashi calculation: https://school.stockcharts.com/doku.php?id=chart_analysis:heikin_ashi 9 | 10 | ha_open calculation based on: https://stackoverflow.com/a/55110393 11 | ha_open = [ calculate first record ][ append remaining records with list comprehension method ] 12 | list comprehension method is significantly faster as a for loop 13 | 14 | result: 15 | ha_open[0] = (bars.open[0] + bars.close[0]) / 2 16 | ha_open[1] = (ha_open[0] + ha_close[0]) / 2 17 | ... 18 | ha_open[last] = ha_open[len(bars)-1] + ha_close[len(bars)-1]) / 2 19 | """ 20 | 21 | bars = bars.copy() 22 | 23 | bars.loc[:, "ha_close"] = bars.loc[:, ["open", "high", "low", "close"]].mean(axis=1) 24 | 25 | ha_open = [(bars.open[0] + bars.close[0]) / 2] 26 | [ha_open.append((ha_open[x] + bars.ha_close[x]) / 2) for x in range(0, len(bars) - 1)] 27 | bars["ha_open"] = ha_open 28 | 29 | bars.loc[:, "ha_high"] = bars.loc[:, ["high", "ha_open", "ha_close"]].max(axis=1) 30 | bars.loc[:, "ha_low"] = bars.loc[:, ["low", "ha_open", "ha_close"]].min(axis=1) 31 | 32 | result = pd.DataFrame( 33 | index=bars.index, 34 | data={ 35 | "open": bars["ha_open"], 36 | "high": bars["ha_high"], 37 | "low": bars["ha_low"], 38 | "close": bars["ha_close"], 39 | }, 40 | ) 41 | 42 | # useful little helpers 43 | result["flat_bottom"] = np.vectorize(_flat_bottom)( 44 | result["close"], result["low"], result["open"], result["high"] 45 | ) 46 | result["flat_top"] = np.vectorize(_flat_top)( 47 | result["close"], result["low"], result["open"], result["high"] 48 | ) 49 | result["small_body"] = np.vectorize(_small_body)( 50 | result["close"], result["low"], result["open"], result["high"] 51 | ) 52 | result["candle"] = np.vectorize(_candle_type)(result["open"], result["close"]) 53 | result["reversal"] = np.vectorize(_reversal)( 54 | result["candle"], shift(result["candle"], 1, cval=np.nan) 55 | ) 56 | 57 | result["lower_wick"] = np.vectorize(_wick_length)( 58 | result["close"], result["low"], result["open"], result["high"], False 59 | ) 60 | result["upper_wick"] = np.vectorize(_wick_length)( 61 | result["close"], result["low"], result["open"], result["high"], True 62 | ) 63 | return result 64 | 65 | 66 | def _reversal(current, prior): 67 | """ 68 | do we observe a reversal 69 | :param current: 70 | :param prior: 71 | :return: 72 | 1 if red to green 73 | 0 if none 74 | -1 if green to red 75 | """ 76 | if current == 1 and prior == -1: 77 | return 1 78 | elif current == -1 and prior == 1: 79 | return -1 80 | else: 81 | return 0 82 | 83 | 84 | def _candle_type(open, close): 85 | """ 86 | 87 | :param open: 88 | :param close: 89 | :return: 1 on green, -1 on red 90 | """ 91 | if open < close: 92 | return 1 93 | else: 94 | return -1 95 | 96 | 97 | def _wick_length(close, low, open, high, upper): 98 | """ 99 | :param close: 100 | :param low: 101 | :param open: 102 | :param high: 103 | :return: 104 | 105 | """ 106 | 107 | if close > open: 108 | top_wick = high - close 109 | bottom_wick = open - low 110 | 111 | else: 112 | top_wick = high - open 113 | bottom_wick = close - low 114 | 115 | if upper: 116 | return top_wick 117 | else: 118 | return bottom_wick 119 | 120 | 121 | def _small_body(close, low, open, high): 122 | """ 123 | do we have a small body in relation to the wicks 124 | :param close: 125 | :param low: 126 | :param open: 127 | :param high: 128 | :return: 129 | 0 if no 130 | 1 if yes (wicks are longer than body) 131 | 132 | """ 133 | size = abs(close - open) 134 | 135 | if close > open: 136 | top_wick = high - close 137 | bottom_wick = open - low 138 | 139 | else: 140 | top_wick = high - open 141 | bottom_wick = close - low 142 | 143 | wick_size = top_wick + bottom_wick 144 | 145 | if wick_size > size: 146 | return 1 147 | else: 148 | return 0 149 | 150 | 151 | def _flat_top(close, low, open, high): 152 | """ 153 | do we have a flat top 154 | 155 | :param close: 156 | :param low: 157 | :param open: 158 | :param high: 159 | :return: 1 if flat and green candle 160 | 0 if no flat top 161 | -1 of flat top and red candle 162 | 163 | """ 164 | if high == close: 165 | return 1 166 | elif high == open: 167 | return -1 168 | else: 169 | return 0 170 | 171 | 172 | def _flat_bottom(close, low, open, high): 173 | """ 174 | do we have a flat bottom 175 | :param close: 176 | :param low: 177 | :param open: 178 | :param high: 179 | :return: 180 | 1 flat and green 181 | -1 flat and red 182 | 0 not flat 183 | """ 184 | if open == low: 185 | return 1 186 | elif close == low: 187 | return -1 188 | else: 189 | return 0 190 | 191 | 192 | def _body_size(open, close): 193 | return abs(open - close) 194 | 195 | 196 | def doji(dataframe, exact=False): 197 | """ 198 | computes the dojis (near by default) or absolute 199 | :param dataframe: 200 | :param exact: 201 | :return: 202 | """ 203 | if exact: 204 | result = dataframe["open"] == dataframe["close"] 205 | else: 206 | result = (dataframe["open"] - dataframe["close"]).abs() <= ( 207 | (dataframe["high"] - dataframe["close"]) * 0.1 208 | ) 209 | 210 | return result.apply(lambda x: 1 if x else 0) 211 | -------------------------------------------------------------------------------- /technical/consensus/__init__.py: -------------------------------------------------------------------------------- 1 | from technical.consensus.consensus import Consensus # noqa: F401 2 | from technical.consensus.movingaverage import MovingAverageConsensus # noqa: F401 3 | from technical.consensus.oscillator import OscillatorConsensus # noqa: F401 4 | -------------------------------------------------------------------------------- /technical/consensus/consensus.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import talib.abstract as ta 3 | 4 | from technical.qtpylib import crossed_above 5 | 6 | 7 | class Consensus: 8 | """ 9 | This file provides you with the consensus indicator and all associated helper methods. 10 | 11 | The idea is based on the concept that, if you have one indicator telling you to buy 12 | things are great. 13 | If 100 indicators are telling you to buy at the same time, things are better. 14 | 15 | If we can now have an easily understandable score, things should be perfect. 16 | 17 | Configuration: 18 | 19 | Each of the utility methods utilizes the default parameters as based in the literature. 20 | Assuming that these are the signals, most trades will use. 21 | 22 | Usage: 23 | 24 | 1. 25 | 26 | from technical.consensus import Consensus 27 | 28 | c = Consensus(dataframe) 29 | 30 | 2. 31 | 32 | call the indicators you would like to have evaluated in your consensus model 33 | with optional parameters. Like the impact 34 | 35 | c.evaluate_rsi() 36 | 37 | 3. call the score method. This will basically compute 2 scores for you, which can be easily 38 | plotted 39 | 40 | c.score() 41 | 42 | if you like to apply some smoothing, you can call 43 | 44 | c.score(smooth=3) 45 | 46 | for example. 47 | 48 | 49 | """ 50 | 51 | def __init__(self, dataframe: pd.DataFrame): 52 | """ 53 | initializes the consensus object. 54 | :param dataframe: dataframe to evaluate 55 | """ 56 | self.dataframe = dataframe.copy() 57 | self.buy_weights = 0 58 | self.sell_weights = 0 59 | 60 | def _weights(self, impact_buy, impact_sell): 61 | """ 62 | helper method to compute total count of utilized indicators and their weights 63 | :param impact_buy: 64 | :param impact_sell: 65 | :return: 66 | """ 67 | self.buy_weights = self.buy_weights + impact_buy 68 | self.sell_weights = self.sell_weights + impact_sell 69 | 70 | def score(self, prefix="consensus", smooth=None): 71 | """ 72 | this computes the consensus score, which should always be between 0 and 100 73 | :param prefix: 74 | :param smooth: Allows to specify an integer for a smoothing interval 75 | :return: 76 | """ 77 | dataframe = self.dataframe 78 | scores = dataframe.filter(regex="^(buy|sell)_.*").fillna(0) 79 | 80 | # computes a score between 0 and 100. The closer to 100 the more agreement 81 | dataframe.loc[:, f"{prefix}_score_sell"] = ( 82 | scores.filter(regex="^(sell)_.*").sum(axis=1) / self.sell_weights * 100 83 | ) 84 | dataframe.loc[:, f"{prefix}_score_buy"] = ( 85 | scores.filter(regex="^(buy)_.*").sum(axis=1) / self.buy_weights * 100 86 | ) 87 | 88 | if smooth is not None: 89 | dataframe[f"{prefix}_score_buy"] = ( 90 | dataframe[f"{prefix}_score_buy"].rolling(smooth).mean() 91 | ) 92 | dataframe[f"{prefix}_score_sell"] = ( 93 | dataframe[f"{prefix}_score_sell"].rolling(smooth).mean() 94 | ) 95 | 96 | return { 97 | "sell": dataframe[f"{prefix}_score_sell"], 98 | "buy": dataframe[f"{prefix}_score_buy"], 99 | "buy_agreement": scores.filter(regex="^(buy)_.*").sum(axis=1), 100 | "sell_agreement": scores.filter(regex="^(sell)_.*").sum(axis=1), 101 | "buy_disagreement": scores.filter(regex="^(buy)_.*").count(axis=1) 102 | - scores.filter(regex="^(buy)_.*").sum(axis=1), 103 | "sell_disagreement": scores.filter(regex="^(sell)_.*").count(axis=1) 104 | - scores.filter(regex="^(sell)_.*").sum(axis=1), 105 | } 106 | 107 | def evaluate_rsi(self, period=14, prefix="rsi", impact_buy=1, impact_sell=1): 108 | """ 109 | evaluates a s 110 | :param dataframe: 111 | :param period: 112 | :param prefix: 113 | :return: 114 | """ 115 | self._weights(impact_buy, impact_sell) 116 | 117 | name = f"{prefix}_{period}" 118 | dataframe = self.dataframe 119 | dataframe[name] = ta.RSI(dataframe, timeperiod=period) 120 | 121 | dataframe.loc[(dataframe[name] < 30), f"buy_{name}"] = 1 * impact_buy 122 | 123 | dataframe.loc[(dataframe[name] > 70), f"sell_{name}"] = 1 * impact_sell 124 | 125 | def evaluate_stoch(self, prefix="stoch", impact_buy=1, impact_sell=1): 126 | """ 127 | evaluates the stochastic fast 128 | :param dataframe: 129 | :param prefix: 130 | :return: 131 | """ 132 | name = f"{prefix}" 133 | self._weights(impact_buy, impact_sell) 134 | dataframe = self.dataframe 135 | stoch_fast = ta.STOCHF(dataframe, 5, 3, 0, 3, 0) 136 | 137 | dataframe[f"{name}_fastd"] = stoch_fast["fastd"] 138 | dataframe[f"{name}_fastk"] = stoch_fast["fastk"] 139 | 140 | dataframe.loc[(dataframe[f"{name}_fastk"] < 20), f"buy_{name}"] = 1 * impact_buy 141 | 142 | dataframe.loc[(dataframe[f"{name}_fastk"] > 80), f"sell_{name}"] = 1 * impact_sell 143 | 144 | def evaluate_stoch_rsi( 145 | self, period=14, smoothd=3, smoothk=3, prefix="stoch_rsi", impact_buy=1, impact_sell=1 146 | ): 147 | """ 148 | evaluates the stochastic rsi fast (TradingView version) 149 | :param dataframe: 150 | :param period: 151 | :param prefix: 152 | :return: 153 | """ 154 | 155 | name = f"{prefix}_{period}" 156 | self._weights(impact_buy, impact_sell) 157 | dataframe = self.dataframe 158 | 159 | # We don't use the talib.STOCHRSI library because it seems 160 | # like the results are not identical to Trading View's version 161 | dataframe[f"rsi_{period}"] = ta.RSI(dataframe, timeperiod=period) 162 | stochrsi = ( 163 | dataframe[f"rsi_{period}"] - dataframe[f"rsi_{period}"].rolling(period).min() 164 | ) / ( 165 | dataframe[f"rsi_{period}"].rolling(period).max() 166 | - dataframe[f"rsi_{period}"].rolling(period).min() 167 | ) 168 | 169 | dataframe[f"{name}_fastk"] = stochrsi.rolling(smoothk).mean() * 100 170 | # The fastd below is not used 171 | dataframe[f"{name}_fastd"] = dataframe[f"{name}_fastk"].rolling(smoothd).mean() 172 | 173 | dataframe.loc[(dataframe[f"{name}_fastk"] < 20), f"buy_{name}"] = 1 * impact_buy 174 | 175 | dataframe.loc[(dataframe[f"{name}_fastk"] > 80), f"sell_{name}"] = 1 * impact_sell 176 | 177 | def evaluate_macd_cross_over(self, prefix="macd_crossover", impact_buy=2, impact_sell=2): 178 | """ 179 | evaluates the MACD if we should buy or sale based on a crossover 180 | :param dataframe: 181 | :param prefix: 182 | :return: 183 | """ 184 | 185 | self._weights(impact_buy, impact_sell) 186 | dataframe = self.dataframe 187 | macd = ta.MACD(dataframe) 188 | dataframe["macd"] = macd["macd"] 189 | dataframe["macdsignal"] = macd["macdsignal"] 190 | dataframe["macdhist"] = macd["macdhist"] 191 | 192 | dataframe.loc[ 193 | (crossed_above(dataframe["macdsignal"], dataframe["macd"])), f"sell_{prefix}" 194 | ] = 1 * impact_sell 195 | 196 | dataframe.loc[ 197 | (crossed_above(dataframe["macd"], dataframe["macdsignal"])), f"buy_{prefix}" 198 | ] = 1 * impact_buy 199 | 200 | return dataframe 201 | 202 | def evaluate_macd(self, prefix="macd", impact_buy=1, impact_sell=1): 203 | """ 204 | evaluates the MACD if we should buy or sale 205 | :param dataframe: 206 | :param prefix: 207 | :return: 208 | """ 209 | 210 | self._weights(impact_buy, impact_sell) 211 | dataframe = self.dataframe 212 | macd = ta.MACD(dataframe) 213 | dataframe["macd"] = macd["macd"] 214 | dataframe["macdsignal"] = macd["macdsignal"] 215 | dataframe["macdhist"] = macd["macdhist"] 216 | 217 | # macd < macds & macd < 0 == sell 218 | dataframe.loc[ 219 | ((dataframe["macd"] < dataframe["macdsignal"]) & (dataframe["macd"] < 0)), 220 | f"sell_{prefix}", 221 | ] = impact_sell 222 | 223 | # macd > macds & macd > 0 == buy 224 | dataframe.loc[ 225 | ((dataframe["macd"] > dataframe["macdsignal"]) & (dataframe["macd"] > 0)), 226 | f"buy_{prefix}", 227 | ] = impact_buy 228 | 229 | return dataframe 230 | 231 | def evaluate_hull(self, period=9, field="close", prefix="hull", impact_buy=1, impact_sell=1): 232 | """ 233 | evaluates a hull moving average 234 | :param dataframe: 235 | :param period: 236 | :param prefix: 237 | :return: 238 | """ 239 | from technical.indicators import hull_moving_average 240 | 241 | self._weights(impact_buy, impact_sell) 242 | dataframe = self.dataframe 243 | name = f"{prefix}_{field}_{period}" 244 | dataframe[name] = hull_moving_average(dataframe, period, field) 245 | 246 | dataframe.loc[(dataframe[name] > dataframe[field]), f"buy_{name}"] = 1 * impact_buy 247 | 248 | dataframe.loc[(dataframe[name] < dataframe[field]), f"sell_{name}"] = 1 * impact_sell 249 | 250 | def evaluate_vwma(self, period=9, prefix="vwma", impact_buy=1, impact_sell=1): 251 | """ 252 | evaluates a volume weighted moving average 253 | :param dataframe: 254 | :param period: 255 | :param prefix: 256 | :return: 257 | """ 258 | from technical.indicators import vwma 259 | 260 | self._weights(impact_buy, impact_sell) 261 | dataframe = self.dataframe 262 | name = f"{prefix}_{period}" 263 | dataframe[name] = vwma(dataframe, period) 264 | 265 | dataframe.loc[(dataframe[name] > dataframe["close"]), f"buy_{name}"] = 1 * impact_buy 266 | 267 | dataframe.loc[(dataframe[name] < dataframe["close"]), f"sell_{name}"] = 1 * impact_sell 268 | 269 | def evaluate_tema(self, period, field="close", prefix="tema", impact_buy=1, impact_sell=1): 270 | """ 271 | evaluates a tema moving average 272 | :param dataframe: 273 | :param period: 274 | :param prefix: 275 | :return: 276 | """ 277 | self._weights(impact_buy, impact_sell) 278 | dataframe = self.dataframe 279 | name = f"{prefix}_{field}_{period}" 280 | dataframe[name] = ta.TEMA(dataframe, timeperiod=period, field=field) 281 | 282 | dataframe.loc[(dataframe[name] < dataframe[field]), f"buy_{name}"] = 1 * impact_buy 283 | 284 | dataframe.loc[(dataframe[name] > dataframe[field]), f"sell_{name}"] = 1 * impact_sell 285 | 286 | def evaluate_ema(self, period, field="close", prefix="ema", impact_buy=1, impact_sell=1): 287 | """ 288 | evaluates a sma moving average 289 | :param dataframe: 290 | :param period: 291 | :param prefix: 292 | :return: 293 | """ 294 | self._weights(impact_buy, impact_sell) 295 | dataframe = self.dataframe 296 | name = f"{prefix}_{field}_{period}" 297 | dataframe[name] = ta.EMA(dataframe, timeperiod=period, field=field) 298 | 299 | dataframe.loc[(dataframe[name] < dataframe[field]), f"buy_{name}"] = 1 * impact_buy 300 | 301 | dataframe.loc[(dataframe[name] > dataframe[field]), f"sell_{name}"] = 1 * impact_sell 302 | 303 | def evaluate_sma(self, period, field="close", prefix="sma", impact_buy=1, impact_sell=1): 304 | """ 305 | evaluates a sma moving average 306 | :param dataframe: 307 | :param period: 308 | :param prefix: 309 | :return: 310 | """ 311 | self._weights(impact_buy, impact_sell) 312 | name = f"{prefix}_{field}_{period}" 313 | dataframe = self.dataframe 314 | dataframe[name] = ta.SMA(dataframe, timeperiod=period, field=field) 315 | 316 | dataframe.loc[(dataframe[name] < dataframe[field]), f"buy_{name}"] = 1 * impact_buy 317 | 318 | dataframe.loc[(dataframe[name] > dataframe[field]), f"sell_{name}"] = 1 * impact_sell 319 | 320 | def evaluate_laguerre(self, prefix="lag", impact_buy=1, impact_sell=1): 321 | """ 322 | evaluates the laguerre 323 | :param dataframe: 324 | :param period: 325 | :param prefix: 326 | :return: 327 | """ 328 | from technical.indicators import laguerre 329 | 330 | self._weights(impact_buy, impact_sell) 331 | dataframe = self.dataframe 332 | name = f"{prefix}" 333 | dataframe[name] = laguerre(dataframe) 334 | 335 | dataframe.loc[(dataframe[name] < 0.1), f"buy_{name}"] = 1 * impact_buy 336 | 337 | dataframe.loc[(dataframe[name] > 0.9), f"sell_{name}"] = 1 * impact_sell 338 | 339 | def evaluate_osc(self, period=12, prefix="osc", impact_buy=1, impact_sell=1): 340 | """ 341 | evaluates the osc 342 | :param dataframe: 343 | :param period: 344 | :param prefix: 345 | :return: 346 | """ 347 | from technical.indicators import osc 348 | 349 | self._weights(impact_buy, impact_sell) 350 | dataframe = self.dataframe 351 | name = f"{prefix}_{period}" 352 | dataframe[name] = osc(dataframe, period) 353 | 354 | dataframe.loc[(dataframe[name] < 0.3), f"buy_{name}"] = 1 * impact_buy 355 | 356 | dataframe.loc[(dataframe[name] > 0.8), f"sell_{name}"] = 1 * impact_sell 357 | 358 | def evaluate_cmf(self, period=12, prefix="cmf", impact_buy=1, impact_sell=1): 359 | """ 360 | evaluates the cmf 361 | :param dataframe: 362 | :param period: 363 | :param prefix: 364 | :return: 365 | """ 366 | from technical.indicators import cmf 367 | 368 | self._weights(impact_buy, impact_sell) 369 | dataframe = self.dataframe 370 | name = f"{prefix}_{period}" 371 | dataframe[name] = cmf(dataframe, period) 372 | 373 | dataframe.loc[(dataframe[name] > 0.5), f"buy_{name}"] = 1 * impact_buy 374 | 375 | dataframe.loc[(dataframe[name] < -0.5), f"sell_{name}"] = 1 * impact_sell 376 | 377 | def evaluate_cci( 378 | self, period=20, prefix="cci", impact_buy=1, impact_sell=1, sell_signal=100, buy_signal=-100 379 | ): 380 | """ 381 | evaluates the cci 382 | :param dataframe: 383 | :param period: 384 | :param prefix: 385 | :return: 386 | """ 387 | 388 | self._weights(impact_buy, impact_sell) 389 | dataframe = self.dataframe 390 | name = f"{prefix}_{period}" 391 | dataframe[name] = ta.CCI(dataframe, timeperiod=period) 392 | 393 | dataframe.loc[(dataframe[name] < buy_signal), f"buy_{name}"] = 1 * impact_buy 394 | 395 | dataframe.loc[(dataframe[name] > sell_signal), f"sell_{name}"] = 1 * impact_sell 396 | 397 | def evaluate_consensus( 398 | self, 399 | consensus, 400 | prefix, 401 | smooth=0, 402 | buy_score=80, 403 | sell_score=80, 404 | impact_buy=1, 405 | impact_sell=1, 406 | average=False, 407 | ): 408 | """ 409 | evaluates another consensus indicator 410 | and integrates it into this indicator 411 | :param dataframe: 412 | :param period: 413 | :param prefix: 414 | :param average: should an average based approach be used or the total computed weight 415 | :return: 416 | """ 417 | 418 | if average: 419 | self._weights(impact_buy, impact_sell) 420 | else: 421 | self._weights(consensus.buy_weights, consensus.sell_weights) 422 | 423 | dataframe = self.dataframe 424 | name = f"{prefix}_" 425 | 426 | result = {} 427 | if smooth > 0: 428 | result = consensus.score(smooth=smooth) 429 | else: 430 | result = consensus.score() 431 | 432 | dataframe[f"{name}_buy"] = result["buy"] 433 | dataframe[f"{name}_sell"] = result["sell"] 434 | 435 | if average: 436 | dataframe.loc[(dataframe[f"{name}_buy"] > buy_score), f"buy_{name}"] = 1 * impact_buy 437 | 438 | dataframe.loc[(dataframe[f"{name}_sell"] >= sell_score), f"sell_{name}"] = ( 439 | 1 * impact_sell 440 | ) 441 | else: 442 | dataframe.loc[(dataframe[f"{name}_buy"] > buy_score), f"buy_{name}"] = ( 443 | consensus.buy_weights * impact_buy 444 | ) 445 | 446 | dataframe.loc[(dataframe[f"{name}_sell"] >= sell_score), f"sell_{name}"] = ( 447 | consensus.sell_weights * impact_sell 448 | ) 449 | 450 | def evaluate_cmo(self, period=20, prefix="cmo", impact_buy=1, impact_sell=1): 451 | """ 452 | evaluates the cmo 453 | :param dataframe: 454 | :param period: 455 | :param prefix: 456 | :return: 457 | """ 458 | self._weights(impact_buy, impact_sell) 459 | dataframe = self.dataframe 460 | name = f"{prefix}_{period}" 461 | dataframe[name] = ta.CMO(dataframe, timeperiod=period) 462 | 463 | dataframe.loc[(dataframe[name] < -50), f"buy_{name}"] = 1 * impact_buy 464 | 465 | dataframe.loc[(dataframe[name] > 50), f"sell_{name}"] = 1 * impact_sell 466 | 467 | def evaluate_ichimoku(self, prefix="ichimoku", impact_buy=1, impact_sell=1): 468 | """ 469 | evaluates the ichimoku 470 | :param dataframe: 471 | :param period: 472 | :param prefix: 473 | :return: 474 | """ 475 | from technical.indicators import ichimoku 476 | 477 | self._weights(impact_buy, impact_sell) 478 | dataframe = self.dataframe 479 | name = f"{prefix}" 480 | ichimoku = ichimoku(dataframe) 481 | 482 | dataframe[f"{name}_tenkan_sen"] = ichimoku["tenkan_sen"] 483 | dataframe[f"{name}_kijun_sen"] = ichimoku["kijun_sen"] 484 | dataframe[f"{name}_senkou_span_a"] = ichimoku["senkou_span_a"] 485 | dataframe[f"{name}_senkou_span_b"] = ichimoku["senkou_span_b"] 486 | dataframe[f"{name}_chikou_span"] = ichimoku["chikou_span"] 487 | 488 | # price is above the cloud 489 | dataframe.loc[ 490 | ( 491 | (dataframe[f"{name}_senkou_span_a"] > dataframe["open"]) 492 | & (dataframe[f"{name}_senkou_span_b"] > dataframe["open"]) 493 | ), 494 | f"buy_{name}", 495 | ] = impact_buy 496 | 497 | # price is below the cloud 498 | dataframe.loc[ 499 | ( 500 | (dataframe[f"{name}_senkou_span_a"] < dataframe["open"]) 501 | & (dataframe[f"{name}_senkou_span_b"] < dataframe["open"]) 502 | ), 503 | f"sell_{name}", 504 | ] = impact_sell 505 | 506 | def evaluate_ultimate_oscilator(self, prefix="uo", impact_buy=1, impact_sell=1): 507 | """ 508 | evaluates the ultimate_oscilator 509 | :param dataframe: 510 | :param period: 511 | :param prefix: 512 | :return: 513 | """ 514 | self._weights(impact_buy, impact_sell) 515 | dataframe = self.dataframe 516 | name = f"{prefix}" 517 | dataframe[name] = ta.ULTOSC(dataframe) 518 | 519 | dataframe.loc[(dataframe[name] < 30), f"buy_{name}"] = 1 * impact_buy 520 | 521 | dataframe.loc[(dataframe[name] > 70), f"sell_{name}"] = 1 * impact_sell 522 | 523 | def evaluate_williams(self, prefix="williams", impact_buy=1, impact_sell=1): 524 | """ 525 | evaluates the williams 526 | :param dataframe: 527 | :param period: 528 | :param prefix: 529 | :return: 530 | """ 531 | from technical.indicators import williams_percent 532 | 533 | self._weights(impact_buy, impact_sell) 534 | dataframe = self.dataframe 535 | name = f"{prefix}" 536 | dataframe[name] = williams_percent(dataframe) 537 | 538 | dataframe.loc[(dataframe[name] < -80), f"buy_{name}"] = 1 * impact_buy 539 | 540 | dataframe.loc[(dataframe[name] > -20), f"sell_{name}"] = 1 * impact_sell 541 | 542 | def evaluate_momentum(self, period=20, prefix="momentum", impact_buy=1, impact_sell=1): 543 | """ 544 | evaluates the momentum 545 | :param dataframe: 546 | :param period: 547 | :param prefix: 548 | :return: 549 | """ 550 | 551 | self._weights(impact_buy, impact_sell) 552 | dataframe = self.dataframe 553 | name = f"{prefix}_{period}" 554 | dataframe[name] = ta.MOM(dataframe, timeperiod=period) 555 | 556 | dataframe.loc[(dataframe[name] > 100), f"buy_{name}"] = 1 * impact_buy 557 | 558 | dataframe.loc[(dataframe[name] < 100), f"sell_{name}"] = 1 * impact_sell 559 | 560 | def evaluate_adx( 561 | self, period=14, prefix="adx", trend_line=25, use_di=True, impact_buy=1, impact_sell=1 562 | ): 563 | """ 564 | evaluates the adx (optionally use plus_di and minus_di to detect buy or sell) 565 | :param dataframe: 566 | :param period: 567 | :param prefix: 568 | :param trend_line: The ADX value at which we consider that a trend is present (Default: 25) 569 | :param use_di: Enable/disable the usage of plus_di and minus_di (Default: Enabled) 570 | :return: 571 | """ 572 | 573 | self._weights(impact_buy, impact_sell) 574 | dataframe = self.dataframe 575 | name = f"{prefix}_{period}" 576 | dataframe[name] = ta.ADX(dataframe, timeperiod=period) 577 | 578 | # We can use PLUS_DI and MINUS_DI to be able to detect if we should buy or sell 579 | # See https://www.investopedia.com/articles/trading/07/adx-trend-indicator.asp 580 | if use_di: 581 | dataframe[f"{name}_plus_di"] = ta.PLUS_DI(dataframe, timeperiod=period) 582 | dataframe[f"{name}_minus_di"] = ta.MINUS_DI(dataframe, timeperiod=period) 583 | 584 | dataframe.loc[ 585 | ( 586 | (dataframe[name] > trend_line) 587 | & (dataframe[f"{name}_plus_di"] > dataframe[f"{name}_minus_di"]) 588 | ), 589 | f"buy_{name}", 590 | ] = 1 * impact_buy 591 | 592 | dataframe.loc[ 593 | ( 594 | (dataframe[name] > trend_line) 595 | & (dataframe[f"{name}_plus_di"] < dataframe[f"{name}_minus_di"]) 596 | ), 597 | f"sell_{name}", 598 | ] = 1 * impact_sell 599 | else: 600 | dataframe.loc[(dataframe[name] > trend_line), f"buy_{name}"] = 1 * impact_buy 601 | 602 | dataframe.loc[(dataframe[name] > trend_line), f"sell_{name}"] = 1 * impact_sell 603 | 604 | def evaluate_ao(self, prefix="ao", impact_buy=1, impact_sell=1): 605 | """ 606 | evaluates the ao (Awesome Oscillator) 607 | :param dataframe: 608 | :param prefix: 609 | :return: 610 | """ 611 | from technical.qtpylib import awesome_oscillator 612 | 613 | self._weights(impact_buy, impact_sell) 614 | dataframe = self.dataframe 615 | name = f"{prefix}" 616 | dataframe[name] = awesome_oscillator(dataframe) 617 | 618 | dataframe.loc[(dataframe[name] > (dataframe[name].shift(1) + 0.05)), f"buy_{name}"] = ( 619 | 1 * impact_buy 620 | ) 621 | 622 | dataframe.loc[(dataframe[name] < (dataframe[name].shift(1) - 0.05)), f"sell_{name}"] = ( 623 | 1 * impact_sell 624 | ) 625 | 626 | def evaluate_bbp(self, period=13, prefix="bbp", impact_buy=1, impact_sell=1): 627 | """ 628 | evaluates the bbp (Bears Bulls Power) 629 | :param dataframe: 630 | :param period: 631 | :param prefix: 632 | :return: 633 | """ 634 | 635 | self._weights(impact_buy, impact_sell) 636 | dataframe = self.dataframe 637 | name = f"{prefix}_{period}" 638 | 639 | # Bears/Bulls Power is using EMA 640 | dataframe[f"{name}_ema"] = ta.EMA(dataframe, timeperiod=period) 641 | dataframe[f"{name}_bulls"] = dataframe["high"] - dataframe[f"{name}_ema"] 642 | dataframe[f"{name}_bears"] = dataframe["low"] - dataframe[f"{name}_ema"] 643 | 644 | dataframe.loc[ 645 | ( 646 | (dataframe[f"{name}_ema"] > dataframe[f"{name}_ema"].shift(1)) 647 | & (dataframe[f"{name}_bulls"] > dataframe[f"{name}_bulls"].shift(1)) 648 | ), 649 | f"buy_{name}", 650 | ] = 1 * impact_buy 651 | 652 | dataframe.loc[ 653 | ( 654 | (dataframe[f"{name}_ema"] < dataframe[f"{name}_ema"].shift(1)) 655 | & (dataframe[f"{name}_bears"] > dataframe[f"{name}_bears"].shift(1)) 656 | ), 657 | f"sell_{name}", 658 | ] = 1 * impact_sell 659 | -------------------------------------------------------------------------------- /technical/consensus/movingaverage.py: -------------------------------------------------------------------------------- 1 | from technical.consensus.consensus import Consensus 2 | 3 | 4 | class MovingAverageConsensus(Consensus): 5 | """ 6 | This provides the consensus MovingAverage based indicators. It's configuration 7 | is identical with the configuration seen here 8 | 9 | https://www.tradingview.com/symbols/BTCUSD/technicals/ 10 | """ 11 | 12 | def __init__(self, dataframe): 13 | super().__init__(dataframe) 14 | 15 | self.evaluate_sma(period=10) 16 | self.evaluate_sma(period=20) 17 | self.evaluate_sma(period=30) 18 | self.evaluate_sma(period=50) 19 | self.evaluate_sma(period=100) 20 | self.evaluate_sma(period=200) 21 | 22 | self.evaluate_ema(period=10) 23 | self.evaluate_ema(period=20) 24 | self.evaluate_ema(period=30) 25 | self.evaluate_ema(period=50) 26 | self.evaluate_ema(period=100) 27 | self.evaluate_ema(period=200) 28 | self.evaluate_ichimoku() 29 | self.evaluate_hull() 30 | self.evaluate_vwma(period=20) 31 | -------------------------------------------------------------------------------- /technical/consensus/oscillator.py: -------------------------------------------------------------------------------- 1 | from technical.consensus.consensus import Consensus 2 | 3 | 4 | class OscillatorConsensus(Consensus): 5 | """ 6 | consensus based indicator, based on several oscillators. Rule of thumb for entry should be 7 | that buy is larger than sell line. 8 | """ 9 | 10 | def __init__(self, dataframe): 11 | super().__init__(dataframe) 12 | self.evaluate_rsi(period=14) 13 | self.evaluate_stoch() 14 | self.evaluate_cci(period=20) 15 | self.evaluate_adx() 16 | # awesome osc 17 | self.evaluate_macd() 18 | self.evaluate_momentum(period=10) 19 | # stoch rsi 20 | self.evaluate_williams() 21 | # bull bear 22 | self.evaluate_ultimate_oscilator() 23 | -------------------------------------------------------------------------------- /technical/consensus/summary.py: -------------------------------------------------------------------------------- 1 | from technical.consensus.consensus import Consensus 2 | from technical.consensus.movingaverage import MovingAverageConsensus 3 | from technical.consensus.oscillator import OscillatorConsensus 4 | 5 | 6 | class SummaryConsensus(Consensus): 7 | """ 8 | an overall consensus of the trading view based configurations 9 | and it's basically a binary operation (on/off switch), meaning it needs 10 | to be combined with a couple of other indicators to avoid false buys. 11 | 12 | """ 13 | 14 | def __init__(self, dataframe): 15 | super().__init__(dataframe) 16 | self.evaluate_consensus(OscillatorConsensus(dataframe), "osc", average=False) 17 | self.evaluate_consensus( 18 | MovingAverageConsensus(dataframe), "moving_average_consensus", average=False 19 | ) 20 | -------------------------------------------------------------------------------- /technical/indicator_helpers.py: -------------------------------------------------------------------------------- 1 | from math import cos, exp, pi, sqrt 2 | 3 | import numpy as np 4 | import talib as ta 5 | from pandas import Series 6 | 7 | 8 | def went_up(series: Series) -> bool: 9 | return series > series.shift(1) 10 | 11 | 12 | def went_down(series: Series) -> bool: 13 | return series < series.shift(1) 14 | 15 | 16 | def ehlers_super_smoother(series: Series, smoothing: float = 6) -> Series: 17 | magic = pi * sqrt(2) / smoothing 18 | a1 = exp(-magic) 19 | coeff2 = 2 * a1 * cos(magic) 20 | coeff3 = -a1 * a1 21 | coeff1 = (1 - coeff2 - coeff3) / 2 22 | 23 | filtered = series.copy() 24 | 25 | for i in range(2, len(series)): 26 | filtered.iloc[i] = ( 27 | coeff1 * (series.iloc[i] + series.iloc[i - 1]) 28 | + coeff2 * filtered.iloc[i - 1] 29 | + coeff3 * filtered.iloc[i - 2] 30 | ) 31 | 32 | return filtered 33 | 34 | 35 | def fishers_inverse(series: Series, smoothing: float = 0) -> np.ndarray: 36 | """ 37 | Does a smoothed fishers inverse transformation. 38 | Can be used with any oscillator that goes from 0 to 100 like RSI or MFI 39 | """ 40 | v1 = 0.1 * (series - 50) 41 | if smoothing > 0: 42 | v2 = ta.WMA(v1.values, timeperiod=smoothing) 43 | else: 44 | v2 = v1 45 | return (np.exp(2 * v2) - 1) / (np.exp(2 * v2) + 1) 46 | -------------------------------------------------------------------------------- /technical/indicators/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa: F401 F403 2 | from .cycle_indicators import * 3 | from .indicators import * 4 | from .momentum import * 5 | from .overlap_studies import * 6 | from .price_transform import * 7 | from .volatility import * 8 | from .volume_indicators import * 9 | -------------------------------------------------------------------------------- /technical/indicators/cycle_indicators.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cycle indicators 3 | """ 4 | 5 | ######################################## 6 | # 7 | # Cycle Indicator Functions 8 | # 9 | 10 | # HT_DCPERIOD Hilbert Transform - Dominant Cycle Period 11 | # HT_DCPHASE Hilbert Transform - Dominant Cycle Phase 12 | # HT_PHASOR Hilbert Transform - Phasor Components 13 | # HT_SINE Hilbert Transform - SineWave 14 | # HT_TRENDMODE Hilbert Transform - Trend vs Cycle Mode 15 | -------------------------------------------------------------------------------- /technical/indicators/indicators.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file contains a collection of common indicators, 3 | which are based on third party or custom libraries 4 | """ 5 | 6 | import math 7 | 8 | import numpy as np 9 | from numpy import ndarray 10 | from pandas import DataFrame, Series 11 | 12 | from .overlap_studies import sma, vwma 13 | 14 | ######################################## 15 | # 16 | # Pattern Recognition Functions 17 | # Statistic Functions 18 | # Math Transform Functions 19 | # Math Operator Functions 20 | # 21 | 22 | 23 | ######################################## 24 | # 25 | # Ichimoku Cloud 26 | # 27 | def ichimoku( 28 | dataframe, conversion_line_period=9, base_line_periods=26, laggin_span=52, displacement=26 29 | ): 30 | """ 31 | Ichimoku cloud indicator 32 | Note: Do not use chikou_span for backtesting. 33 | It looks into the future, is not printed by most charting platforms. 34 | It is only useful for visual analysis 35 | 36 | Usage: 37 | ichi = ichimoku(dataframe) 38 | dataframe['tenkan_sen'] = ichi['tenkan_sen'] 39 | dataframe['kijun_sen'] = ichi['kijun_sen'] 40 | dataframe['senkou_span_a'] = ichi['senkou_span_a'] 41 | dataframe['senkou_span_b'] = ichi['senkou_span_b'] 42 | dataframe['cloud_green'] = ichi['cloud_green'] 43 | dataframe['cloud_red'] = ichi['cloud_red'] 44 | 45 | :param dataframe: Dataframe containing OHLCV data 46 | :param conversion_line_period: Conversion line Period (defaults to 9) 47 | :param base_line_periods: Base line Periods (defaults to 26) 48 | :param laggin_span: Lagging span period 49 | :param displacement: Displacement (shift) - defaults to 26 50 | :return: Dict containing the following keys: 51 | tenkan_sen, kijun_sen, senkou_span_a, senkou_span_b, leading_senkou_span_a, 52 | leading_senkou_span_b, chikou_span, cloud_green, cloud_red 53 | """ 54 | 55 | tenkan_sen = ( 56 | dataframe["high"].rolling(window=conversion_line_period).max() 57 | + dataframe["low"].rolling(window=conversion_line_period).min() 58 | ) / 2 59 | 60 | kijun_sen = ( 61 | dataframe["high"].rolling(window=base_line_periods).max() 62 | + dataframe["low"].rolling(window=base_line_periods).min() 63 | ) / 2 64 | 65 | leading_senkou_span_a = (tenkan_sen + kijun_sen) / 2 66 | 67 | leading_senkou_span_b = ( 68 | dataframe["high"].rolling(window=laggin_span).max() 69 | + dataframe["low"].rolling(window=laggin_span).min() 70 | ) / 2 71 | 72 | senkou_span_a = leading_senkou_span_a.shift(displacement - 1) 73 | 74 | senkou_span_b = leading_senkou_span_b.shift(displacement - 1) 75 | 76 | chikou_span = dataframe["close"].shift(-displacement + 1) 77 | 78 | cloud_green = senkou_span_a > senkou_span_b 79 | cloud_red = senkou_span_b > senkou_span_a 80 | 81 | return { 82 | "tenkan_sen": tenkan_sen, 83 | "kijun_sen": kijun_sen, 84 | "senkou_span_a": senkou_span_a, 85 | "senkou_span_b": senkou_span_b, 86 | "leading_senkou_span_a": leading_senkou_span_a, 87 | "leading_senkou_span_b": leading_senkou_span_b, 88 | "chikou_span": chikou_span, 89 | "cloud_green": cloud_green, 90 | "cloud_red": cloud_red, 91 | } 92 | 93 | 94 | ######################################## 95 | # 96 | # Laguerre RSI 97 | # 98 | def laguerre(dataframe, gamma=0.75, smooth=1, debug=False) -> Series: 99 | """ 100 | laguerre RSI 101 | Author Creslin 102 | Original Author: John Ehlers 1979 103 | 104 | :param dataframe: df 105 | :param gamma: Between 0 and 1, default 0.75 106 | :param smooth: 1 is off. Valid values over 1 are alook back smooth for an ema 107 | :param debug: Bool, prints to console 108 | :return: Laguerre RSI:values 0 to +1 109 | """ 110 | """ 111 | Laguerra RSI 112 | How to trade lrsi: (TL, DR) buy on the flat 0, sell on the drop from top, 113 | not when touch the top 114 | http://systemtradersuccess.com/testing-laguerre-rsi/ 115 | 116 | http://www.davenewberg.com/Trading/TS_Code/Ehlers_Indicators/Laguerre_RSI.html 117 | """ 118 | 119 | df = dataframe 120 | g = gamma 121 | smooth = smooth 122 | debug = debug 123 | if debug: 124 | from pandas import set_option 125 | 126 | set_option("display.max_rows", 2000) 127 | set_option("display.max_columns", 8) 128 | 129 | """ 130 | Vectorised pandas or numpy calculations are not used 131 | in Laguerre as L0 is self referencing. 132 | Therefore we use an intertuples loop as next best option. 133 | """ 134 | lrsi_l = [] 135 | L0, L1, L2, L3 = 0.0, 0.0, 0.0, 0.0 136 | for row in df.itertuples(index=True, name="lrsi"): 137 | """ 138 | Original Pine Logic Block1 139 | p = close 140 | L0 = ((1 - g)*p)+(g*nz(L0[1])) 141 | L1 = (-g*L0)+nz(L0[1])+(g*nz(L1[1])) 142 | L2 = (-g*L1)+nz(L1[1])+(g*nz(L2[1])) 143 | L3 = (-g*L2)+nz(L2[1])+(g*nz(L3[1])) 144 | """ 145 | # Feed back loop 146 | L0_1, L1_1, L2_1, L3_1 = L0, L1, L2, L3 147 | 148 | L0 = (1 - g) * row.close + g * L0_1 149 | L1 = -g * L0 + L0_1 + g * L1_1 150 | L2 = -g * L1 + L1_1 + g * L2_1 151 | L3 = -g * L2 + L2_1 + g * L3_1 152 | 153 | """ Original Pinescript Block 2 154 | cu=(L0 > L1? L0 - L1: 0) + (L1 > L2? L1 - L2: 0) + (L2 > L3? L2 - L3: 0) 155 | cd=(L0 < L1? L1 - L0: 0) + (L1 < L2? L2 - L1: 0) + (L2 < L3? L3 - L2: 0) 156 | """ 157 | cu = 0.0 158 | cd = 0.0 159 | if L0 >= L1: 160 | cu = L0 - L1 161 | else: 162 | cd = L1 - L0 163 | 164 | if L1 >= L2: 165 | cu = cu + L1 - L2 166 | else: 167 | cd = cd + L2 - L1 168 | 169 | if L2 >= L3: 170 | cu = cu + L2 - L3 171 | else: 172 | cd = cd + L3 - L2 173 | 174 | """Original Pinescript Block 3 175 | lrsi=ema((cu+cd==0? -1: cu+cd)==-1? 0: (cu/(cu+cd==0? -1: cu+cd)), smooth) 176 | """ 177 | if (cu + cd) != 0: 178 | lrsi_l.append(cu / (cu + cd)) 179 | else: 180 | lrsi_l.append(0) 181 | 182 | return Series(lrsi_l) 183 | 184 | 185 | ######################################## 186 | # 187 | # Madrid Functions 188 | # 189 | def mmar(dataframe, matype="EMA", src="close", debug=False): # noqa: C901 190 | """ 191 | Madrid Moving Average Ribbon 192 | 193 | Returns: MMAR 194 | """ 195 | """ 196 | Author(Freqtrade): Creslinux 197 | Original Author(TrdingView): "Madrid" 198 | 199 | Pinescript from TV Source Code and Description 200 | // 201 | // Madrid : 17/OCT/2014 22:51M: Moving Average Ribbon : 2.0 : MMAR 202 | // http://madridjourneyonws.blogspot.com/ 203 | // 204 | // This plots a moving average ribbon, either exponential or standard. 205 | // This study is best viewed with a dark background. It provides an easy 206 | // and fast way to determine the trend direction and possible reversals. 207 | // 208 | // Lime : Uptrend. Long trading 209 | // Green : Reentry (buy the dip) or downtrend reversal warning 210 | // Red : Downtrend. Short trading 211 | // Maroon : Short Reentry (sell the peak) or uptrend reversal warning 212 | // 213 | // To best determine if this is a reentry point or a trend reversal 214 | // the MMARB (Madrid Moving Average Ribbon Bar) study is used. 215 | // This is the bar located at the bottom. This bar signals when a 216 | // current trend reentry is found (partially filled with opposite dark color) 217 | // or when a trend reversal is ahead (completely filled with opposite dark color). 218 | // 219 | 220 | study(title="Madrid Moving Average Ribbon", shorttitle="MMAR", overlay=true) 221 | exponential = input(true, title="Exponential MA") 222 | 223 | src = close 224 | 225 | ma05 = exponential ? ema(src, 05) : sma(src, 05) 226 | ma10 = exponential ? ema(src, 10) : sma(src, 10) 227 | ma15 = exponential ? ema(src, 15) : sma(src, 15) 228 | ma20 = exponential ? ema(src, 20) : sma(src, 20) 229 | ma25 = exponential ? ema(src, 25) : sma(src, 25) 230 | ma30 = exponential ? ema(src, 30) : sma(src, 30) 231 | ma35 = exponential ? ema(src, 35) : sma(src, 35) 232 | ma40 = exponential ? ema(src, 40) : sma(src, 40) 233 | ma45 = exponential ? ema(src, 45) : sma(src, 45) 234 | ma50 = exponential ? ema(src, 50) : sma(src, 50) 235 | ma55 = exponential ? ema(src, 55) : sma(src, 55) 236 | ma60 = exponential ? ema(src, 60) : sma(src, 60) 237 | ma65 = exponential ? ema(src, 65) : sma(src, 65) 238 | ma70 = exponential ? ema(src, 70) : sma(src, 70) 239 | ma75 = exponential ? ema(src, 75) : sma(src, 75) 240 | ma80 = exponential ? ema(src, 80) : sma(src, 80) 241 | ma85 = exponential ? ema(src, 85) : sma(src, 85) 242 | ma90 = exponential ? ema(src, 90) : sma(src, 90) 243 | ma100 = exponential ? ema(src, 100) : sma(src, 100) 244 | 245 | leadMAColor = change(ma05)>=0 and ma05>ma100 ? lime 246 | : change(ma05)<0 and ma05>ma100 ? maroon 247 | : change(ma05)<=0 and ma05=0 and ma05 251 | change(ma)>=0 and ma05>maRef ? lime 252 | : change(ma)<0 and ma05>maRef ? maroon 253 | : change(ma)<=0 and ma05=0 and ma05=0 and ma05>ma100 ? lime +2 318 | : change(ma05)<0 and ma05>ma100 ? maroon -1 319 | : change(ma05)<=0 and ma05=0 and ma05= 0 and (x["ma05"] > x["ma100"]): 326 | # Lime: Uptrend.Long trading 327 | x["leadMA"] = "lime" 328 | return x["leadMA"] 329 | elif (x["ma05"] - x["ma05l"]) < 0 and (x["ma05"] > x["ma100"]): 330 | # Maroon : Short Reentry (sell the peak) or uptrend reversal warning 331 | x["leadMA"] = "maroon" 332 | return x["leadMA"] 333 | elif (x["ma05"] - x["ma05l"]) <= 0 and (x["ma05"] < x["ma100"]): 334 | # Red : Downtrend. Short trading 335 | x["leadMA"] = "red" 336 | return x["leadMA"] 337 | elif (x["ma05"] - x["ma05l"]) >= 0 and (x["ma05"] < x["ma100"]): 338 | # Green: Reentry(buy the dip) or downtrend reversal warning 339 | x["leadMA"] = "green" 340 | return x["leadMA"] 341 | else: 342 | # If its great it means not enough ticker data for lookback 343 | x["leadMA"] = "grey" 344 | return x["leadMA"] 345 | 346 | df["leadMA"] = df.apply(leadMAc, axis=1) 347 | 348 | """ Logic for MAs 349 | : change(ma)>=0 and ma>ma100 ? lime 350 | : change(ma)<0 and ma>ma100 ? maroon 351 | : change(ma)<=0 and ma=0 and ma= 0 and (x[ma] > x["ma100"]): 361 | # Lime: Uptrend.Long trading 362 | x[col_label] = "lime" 363 | return x[col_label] 364 | elif (x[ma] - x[col_label_1]) < 0 and (x[ma] > x["ma100"]): 365 | # Maroon : Short Reentry (sell the peak) or uptrend reversal warning 366 | x[col_label] = "maroon" 367 | return x[col_label] 368 | 369 | elif (x[ma] - x[col_label_1]) <= 0 and (x[ma] < x["ma100"]): 370 | # Red : Downtrend. Short trading 371 | x[col_label] = "red" 372 | return x[col_label] 373 | 374 | elif (x[ma] - x[col_label_1]) >= 0 and (x[ma] < x["ma100"]): 375 | # Green: Reentry(buy the dip) or downtrend reversal warning 376 | x[col_label] = "green" 377 | return x[col_label] 378 | else: 379 | # If its great it means not enough ticker data for lookback 380 | x[col_label] = "grey" 381 | return x[col_label] 382 | 383 | df["ma10_c"] = df.apply(maColor, ma="ma10", axis=1) 384 | df["ma20_c"] = df.apply(maColor, ma="ma20", axis=1) 385 | df["ma30_c"] = df.apply(maColor, ma="ma30", axis=1) 386 | df["ma40_c"] = df.apply(maColor, ma="ma40", axis=1) 387 | df["ma50_c"] = df.apply(maColor, ma="ma50", axis=1) 388 | df["ma60_c"] = df.apply(maColor, ma="ma60", axis=1) 389 | df["ma70_c"] = df.apply(maColor, ma="ma70", axis=1) 390 | df["ma80_c"] = df.apply(maColor, ma="ma80", axis=1) 391 | df["ma90_c"] = df.apply(maColor, ma="ma90", axis=1) 392 | 393 | if debug: 394 | from pandas import set_option 395 | 396 | set_option("display.max_rows", 10) 397 | print( 398 | df[ 399 | [ 400 | "date", 401 | "ma05", 402 | "ma05l", 403 | "leadMA", 404 | "ma10", 405 | "ma10l", 406 | "ma10_c", 407 | # "ma20", "ma20l", "ma20_c", 408 | # "ma30", "ma30l", "ma30_c", 409 | # "ma40", "ma40l", "ma40_c", 410 | # "ma50", "ma50l", "ma50_c", 411 | # "ma60", "ma60l", "ma60_c", 412 | # "ma70", "ma70l", "ma70_c", 413 | # "ma80", "ma80l", "ma80_c", 414 | "ma90", 415 | "ma90l", 416 | "ma90_c", 417 | "ma100", 418 | ] 419 | ].tail(200) 420 | ) 421 | 422 | print( 423 | df[ 424 | [ 425 | "date", 426 | "close", 427 | "leadMA", 428 | "ma10_c", 429 | "ma20_c", 430 | "ma30_c", 431 | "ma40_c", 432 | "ma50_c", 433 | "ma60_c", 434 | "ma70_c", 435 | "ma80_c", 436 | "ma90_c", 437 | ] 438 | ].tail(684) 439 | ) 440 | 441 | return ( 442 | df["leadMA"], 443 | df["ma10_c"], 444 | df["ma20_c"], 445 | df["ma30_c"], 446 | df["ma40_c"], 447 | df["ma50_c"], 448 | df["ma60_c"], 449 | df["ma70_c"], 450 | df["ma80_c"], 451 | df["ma90_c"], 452 | ) 453 | 454 | 455 | def madrid_sqz(datafame, length=34, src="close", ref=13, sqzLen=5): 456 | """ 457 | Squeeze Madrid Indicator 458 | 459 | Author: Creslinux 460 | Original Author: Madrid - Tradingview 461 | https://www.tradingview.com/script/9bUUSzM3-Madrid-Trend-Squeeze/ 462 | 463 | :param datafame: 464 | :param length: min 14 - default 34 465 | :param src: default close 466 | :param ref: default 13 467 | :param sqzLen: default 5 468 | :return: df['sqz_cma_c'], df['sqz_rma_c'], df['sqz_sma_c'] 469 | 470 | 471 | There are seven colors used for the study 472 | 473 | Green : Uptrend in general 474 | Lime : Spots the current uptrend leg 475 | Aqua : The maximum profitability of the leg in a long trade 476 | The Squeeze happens when Green+Lime+Aqua are aligned (the larger the values the better) 477 | 478 | Maroon : Downtrend in general 479 | Red : Spots the current downtrend leg 480 | Fuchsia: The maximum profitability of the leg in a short trade 481 | The Squeeze happens when Maroon+Red+Fuchsia are aligned (the larger the values the better) 482 | 483 | Yellow : The trend has come to a pause and it is either a reversal warning or a continuation. 484 | These are the entry, re-entry or closing position points. 485 | """ 486 | 487 | """ 488 | Original Pinescript source code 489 | 490 | ma = ema(src, len) 491 | closema = close - ma 492 | refma = ema(src, ref) - ma 493 | sqzma = ema(src, sqzLen) - ma 494 | 495 | hline(0) 496 | plotcandle(0, closema, 0, closema, color=closema >= 0?aqua: fuchsia) 497 | plotcandle(0, sqzma, 0, sqzma, color=sqzma >= 0?lime: red) 498 | plotcandle(0, refma, 0, refma, color=(refma >= 0 and closema < refma) or ( 499 | refma < 0 and closema > refma) ? yellow: refma >= 0 ? green: maroon) 500 | """ 501 | import talib as ta 502 | 503 | len = length 504 | src = src 505 | ref = ref 506 | sqzLen = sqzLen 507 | df = datafame 508 | ema = ta.EMA 509 | 510 | """ Original code logic 511 | ma = ema(src, len) 512 | closema = close - ma 513 | refma = ema(src, ref) - ma 514 | sqzma = ema(src, sqzLen) - ma 515 | """ 516 | df["sqz_ma"] = ema(df[src], len) 517 | df["sqz_cma"] = df["close"] - df["sqz_ma"] 518 | df["sqz_rma"] = ema(df[src], ref) - df["sqz_ma"] 519 | df["sqz_sma"] = ema(df[src], sqzLen) - df["sqz_ma"] 520 | 521 | """ Original code logic 522 | plotcandle(0, closema, 0, closema, color=closema >= 0?aqua: fuchsia) 523 | plotcandle(0, sqzma, 0, sqzma, color=sqzma >= 0?lime: red) 524 | 525 | plotcandle(0, refma, 0, refma, color= 526 | (refma >= 0 and closema < refma) or (refma < 0 and closema > refma) ? yellow: 527 | refma >= 0 ? green: maroon) 528 | """ 529 | 530 | # print(df[['sqz_cma', 'sqz_rma', 'sqz_sma']]) 531 | 532 | def sqz_cma_c(x): 533 | if x["sqz_cma"] >= 0: 534 | x["sqz_cma_c"] = "aqua" 535 | return x["sqz_cma_c"] 536 | else: 537 | x["sqz_cma_c"] = "fuchsia" 538 | return x["sqz_cma_c"] 539 | 540 | df["sqz_cma_c"] = df.apply(sqz_cma_c, axis=1) 541 | 542 | def sqz_sma_c(x): 543 | if x["sqz_sma"] >= 0: 544 | x["sqz_sma_c"] = "lime" 545 | return x["sqz_sma_c"] 546 | else: 547 | x["sqz_sma_c"] = "red" 548 | return x["sqz_sma_c"] 549 | 550 | df["sqz_sma_c"] = df.apply(sqz_sma_c, axis=1) 551 | 552 | def sqz_rma_c(x): 553 | if x["sqz_rma"] >= 0 and x["sqz_cma"] < x["sqz_rma"]: 554 | x["sqz_rma_c"] = "yellow" 555 | return x["sqz_rma_c"] 556 | elif x["sqz_rma"] < 0 and x["sqz_cma"] > x["sqz_rma"]: 557 | x["sqz_rma_c"] = "yellow" 558 | return x["sqz_rma_c"] 559 | elif x["sqz_rma"] >= 0: 560 | x["sqz_rma_c"] = "green" 561 | return x["sqz_rma_c"] 562 | else: 563 | x["sqz_rma_c"] = "maroon" 564 | return x["sqz_rma_c"] 565 | 566 | df["sqz_rma_c"] = df.apply(sqz_rma_c, axis=1) 567 | 568 | # print(df[['sqz_cma_c', 'sqz_rma_c', 'sqz_sma_c']]) 569 | return df["sqz_cma_c"], df["sqz_rma_c"], df["sqz_sma_c"] 570 | 571 | 572 | ######################################## 573 | # 574 | # Other Indicator Functions / Unsorted 575 | # 576 | def osc(dataframe, periods=14) -> ndarray: 577 | """ 578 | 1. Calculating DM (i). 579 | If HIGH (i) > HIGH (i - 1), DM (i) = HIGH (i) - HIGH (i - 1), otherwise DM (i) = 0. 580 | 2. Calculating DMn (i). 581 | If LOW (i) < LOW (i - 1), DMn (i) = LOW (i - 1) - LOW (i), otherwise DMn (i) = 0. 582 | 3. Calculating value of OSC: 583 | OSC (i) = SMA (DM, N) / (SMA (DM, N) + SMA (DMn, N)). 584 | 585 | :param dataframe: 586 | :param periods: 587 | :return: 588 | """ 589 | df = dataframe 590 | df["DM"] = (df["high"] - df["high"].shift()).apply(lambda x: max(x, 0)) 591 | df["DMn"] = (df["low"].shift() - df["low"]).apply(lambda x: max(x, 0)) 592 | return Series.rolling_mean(df.DM, periods) / ( 593 | Series.rolling_mean(df.DM, periods) + Series.rolling_mean(df.DMn, periods) 594 | ) 595 | 596 | 597 | def vfi(dataframe, length=130, coef=0.2, vcoef=2.5, signalLength=5, smoothVFI=False): 598 | """ 599 | Volume Flow Indicator conversion 600 | 601 | Author: creslinux, June 2018 - Python 602 | Original Author: Chris Moody, TradingView - Pinescript 603 | To return vfi, vfima and histogram 604 | 605 | A simplified interpretation of the VFI is: 606 | * Values above zero indicate a bullish state and the crossing of the zero line is the trigger 607 | or buy signal. 608 | * The strongest signal with all money flow indicators is of course divergence. 609 | * A crossover of vfi > vfima is uptrend 610 | * A crossunder of vfima > vfi is downtrend 611 | * smoothVFI can be set to smooth for a cleaner plot to ease false signals 612 | * histogram can be used against self -1 to check if upward or downward momentum 613 | 614 | 615 | Call from strategy to populate vfi, vfima, vfi_hist into dataframe 616 | 617 | Example how to call: 618 | # Volume Flow Index: Add VFI, VFIMA, Histogram to DF 619 | dataframe['vfi'], dataframe['vfima'], dataframe['vfi_hist'] = \ 620 | vfi(dataframe, length=130, coef=0.2, vcoef=2.5, signalLength=5, smoothVFI=False) 621 | 622 | :param dataframe: 623 | :param length: - VFI Length - 130 default 624 | :param coef: - price coef - 0.2 default 625 | :param vcoef: - volume coef - 2.5 default 626 | :param signalLength: - 5 default 627 | :param smoothVFI: bool - False default 628 | :return: vfi, vfima, vfi_hist 629 | """ 630 | 631 | """" 632 | Original Pinescript 633 | From: https://www.tradingview.com/script/MhlDpfdS-Volume-Flow-Indicator-LazyBear/ 634 | 635 | length = input(130, title="VFI length") 636 | coef = input(0.2) 637 | vcoef = input(2.5, title="Max. vol. cutoff") 638 | signalLength=input(5) 639 | smoothVFI=input(false, type=bool) 640 | 641 | #### Conversion summary to python 642 | - ma(x,y) => smoothVFI ? sma(x,y) : x // Added as smoothVFI test on vfi 643 | 644 | - typical = hlc3 // Added to DF as HLC 645 | - inter = log(typical) - log(typical[1]) // Added to DF as inter 646 | - vinter = stdev(inter, 30) // Added to DF as vinter 647 | - cutoff = coef * vinter * close // Added to DF as cutoff 648 | - vave = sma(volume, length)[1] // Added to DF as vave 649 | - vmax = vave * vcoef // Added to Df as vmax 650 | - vc = iff(volume < vmax, volume, vmax) // Added np.where test, result in DF as vc 651 | - mf = typical - typical[1] // Added into DF as mf - typical is hlc3 652 | - vcp = iff(mf > cutoff, vc, iff(mf < -cutoff, -vc, 0)) // added in def vcp, in DF as vcp 653 | 654 | - vfi = ma(sum(vcp, length) / vave, 3) // Added as DF vfi. 655 | Will sma vfi 3 if smoothVFI flag set 656 | - vfima = ema(vfi, signalLength) // added to DF as vfima 657 | - d = vfi-vfima // Added to df as histogram 658 | 659 | ### Pinscript plotout - nothing to do here for freqtrade. 660 | plot(0, color=gray, style=3) 661 | showHisto=input(false, type=bool) 662 | plot(showHisto ? d : na, style=histogram, color=gray, linewidth=3, transp=50) 663 | plot( vfima , title="EMA of vfi", color=orange) 664 | plot( vfi, title="vfi", color=green,linewidth=2) 665 | """ 666 | 667 | import talib as ta 668 | from numpy import where 669 | 670 | length = length 671 | coef = coef 672 | vcoef = vcoef 673 | signalLength = signalLength 674 | smoothVFI = smoothVFI 675 | df = dataframe 676 | # Add hlc3 and populate inter to the dataframe 677 | df["hlc"] = ((df["high"] + df["low"] + df["close"]) / 3).astype(float) 678 | df["inter"] = df["hlc"].map(math.log) - df["hlc"].shift(+1).map(math.log) 679 | df["vinter"] = df["inter"].rolling(30).std(ddof=0) 680 | df["cutoff"] = coef * df["vinter"] * df["close"] 681 | # Vave is to be calculated on volume of the past bar 682 | df["vave"] = ta.SMA(df["volume"].shift(+1), timeperiod=length) 683 | df["vmax"] = df["vave"] * vcoef 684 | df["vc"] = where((df["volume"] < df["vmax"]), df["volume"], df["vmax"]) 685 | df["mf"] = df["hlc"] - df["hlc"].shift(+1) 686 | 687 | # more logic for vcp, so create a def and df.apply it 688 | def vcp(x): 689 | if x["mf"] > x["cutoff"]: 690 | return x["vc"] 691 | elif x["mf"] < -(x["cutoff"]): 692 | return -(x["vc"]) 693 | else: 694 | return 0 695 | 696 | df["vcp"] = df.apply(vcp, axis=1) 697 | # vfi has a smooth option passed over def call, sma if set 698 | df["vfi"] = (df["vcp"].rolling(length).sum()) / df["vave"] 699 | if smoothVFI is True: 700 | df["vfi"] = ta.SMA(df["vfi"], timeperiod=3) 701 | df["vfima"] = ta.EMA(df["vfi"], signalLength) 702 | df["vfi_hist"] = df["vfi"] - df["vfima"] 703 | 704 | # clean up columns used vfi calculation but not needed for strategy 705 | df.drop("hlc", axis=1, inplace=True) 706 | df.drop("inter", axis=1, inplace=True) 707 | df.drop("vinter", axis=1, inplace=True) 708 | df.drop("cutoff", axis=1, inplace=True) 709 | df.drop("vave", axis=1, inplace=True) 710 | df.drop("vmax", axis=1, inplace=True) 711 | df.drop("vc", axis=1, inplace=True) 712 | df.drop("mf", axis=1, inplace=True) 713 | df.drop("vcp", axis=1, inplace=True) 714 | 715 | return df["vfi"], df["vfima"], df["vfi_hist"] 716 | 717 | 718 | def stc(dataframe, fast=23, slow=50, length=10): 719 | # First, the 23-period and the 50-period EMA and the MACD values are calculated: 720 | # EMA1 = EMA (Close, Short Length); 721 | # EMA2 = EMA (Close, Long Length); 722 | # MACD = EMA1 – EMA2. 723 | # Second, the 10-period Stochastic from the MACD values is calculated: 724 | # %K (MACD) = %KV (MACD, 10); 725 | # %D (MACD) = %DV (MACD, 10); 726 | # Schaff = 100 x (MACD – %K (MACD)) / (%D (MACD) – %K (MACD)) 727 | 728 | import talib.abstract as ta 729 | 730 | MACD = ta.EMA(dataframe, timeperiod=fast) - ta.EMA(dataframe, timeperiod=slow) 731 | STOK = ( 732 | (MACD - MACD.rolling(window=length).min()) 733 | / (MACD.rolling(window=length).max() - MACD.rolling(window=length).min()) 734 | ) * 100 735 | STOD = STOK.rolling(window=length).mean() 736 | dataframe["stc"] = 100 * (MACD - (STOK * MACD)) / ((STOD * MACD) - (STOK * MACD)) 737 | 738 | return dataframe["stc"] 739 | 740 | 741 | def vpcii(dataframe, period_short=5, period_long=20, hist=8, hist_long=30): 742 | """ 743 | improved version of the vpcii 744 | 745 | 746 | :param dataframe: 747 | :param period_short: 748 | :param period_long: 749 | :param hist: 750 | :return: 751 | """ 752 | 753 | dataframe = dataframe.copy() 754 | dataframe["vpci"] = vpci(dataframe, period_short, period_long) 755 | dataframe["vpcis"] = dataframe["vpci"].rolling(hist).mean() 756 | dataframe["vpci_hist"] = (dataframe["vpci"] - dataframe["vpcis"]).pct_change() 757 | 758 | return dataframe["vpci_hist"].abs() 759 | 760 | 761 | def vpci(dataframe, period_short=5, period_long=20): 762 | """ 763 | volume confirming indicator as seen here 764 | 765 | https://www.tradingview.com/script/lmTqKOsa-Indicator-Volume-Price-Confirmation-Indicator-VPCI/ 766 | 767 | 768 | should be used with bollinger bands, for deccision making 769 | :param dataframe: 770 | :param period_long: 771 | :param period_short: 772 | :return: 773 | """ 774 | 775 | vpc = vwma(dataframe, period_long) - sma(dataframe, period_long) 776 | vpr = vwma(dataframe, period_short) / sma(dataframe, period_short) 777 | vm = sma(dataframe, period_short, field="volume") / sma(dataframe, period_long, field="volume") 778 | 779 | vpci = vpc * vpr * vm 780 | 781 | return vpci 782 | 783 | 784 | def fibonacci_retracements(df, field="close") -> DataFrame: 785 | # Common Fibonacci replacement thresholds: 786 | # 1.0, sqrt(F_n / F_{n+1}), F_n / F_{n+1}, 0.5, F_n / F_{n+2}, F_n / F_{n+3}, 0.0 787 | thresholds = [1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0] 788 | 789 | window_min, window_max = df[field].min(), df[field].max() 790 | # fib_levels = [window_min + t * (window_max - window_min) for t in thresholds] 791 | 792 | # Scale data to match to thresholds 793 | # Can be returned instead if one is looking at the movement between levels 794 | data = (df[field] - window_min) / (window_max - window_min) 795 | 796 | # Otherwise, we return a step indicator showing the fibonacci level 797 | # which each candle exceeds 798 | return data.apply(lambda x: max(t for t in thresholds if x >= t)) 799 | 800 | 801 | def return_on_investment(dataframe, decimals=2) -> DataFrame: 802 | """ 803 | Simple ROI indicator. 804 | 805 | :param dataframe: 806 | :param decimals: 807 | :return: 808 | """ 809 | 810 | close = np.array(dataframe["close"]) 811 | buy = np.array(dataframe["buy"]) 812 | buy_idx = np.where(buy == 1)[0] 813 | roi = np.zeros(len(close)) 814 | if len(buy_idx) > 0: 815 | # get chunks starting with a buy signal 816 | # everything before the first buy signal is discarded 817 | buy_chunks = np.split(close, buy_idx)[1:] 818 | for idx, chunk in zip(buy_idx, buy_chunks): 819 | # round ROI to avoid float accuracy problems 820 | chunk_roi = np.round(100.0 * (chunk / chunk[0] - 1.0), decimals) 821 | roi[idx : idx + len(chunk)] = chunk_roi 822 | 823 | dataframe["roi"] = roi 824 | 825 | return dataframe 826 | 827 | 828 | def td_sequential(dataframe): 829 | """ 830 | TD Sequential 831 | Author(Freqtrade): MichealReed 832 | Original Author: Tom Demark 833 | 834 | 835 | :param dataframe: dataframe 836 | :return: Dataframe with additional column TD_count 837 | content: TD Sequential:values -9 to +9 838 | """ 839 | 840 | # Copy DF 841 | df = dataframe.copy() 842 | 843 | condv = df["volume"] > 0 844 | cond1 = df["close"] > df["close"].shift(4) 845 | cond2 = df["close"] < df["close"].shift(4) 846 | 847 | df["cond_tdb_a"] = (df.groupby(((cond1)[condv]).cumsum()).cumcount() % 10 == 0).cumsum() 848 | df["cond_tds_a"] = (df.groupby(((cond2)[condv]).cumsum()).cumcount() % 10 == 0).cumsum() 849 | df["cond_tdb_b"] = (df.groupby(((cond1)[condv]).cumsum()).cumcount() % 10 != 0).cumsum() 850 | df["cond_tds_b"] = (df.groupby(((cond2)[condv]).cumsum()).cumcount() % 10 != 0).cumsum() 851 | 852 | df["tdb_a"] = df.groupby(df["cond_tdb_a"]).cumcount() 853 | df["tds_a"] = df.groupby(df["cond_tds_a"]).cumcount() 854 | 855 | df["tdb_b"] = df.groupby(df["cond_tdb_b"]).cumcount() 856 | df["tds_b"] = df.groupby(df["cond_tds_b"]).cumcount() 857 | 858 | df["tdc"] = df["tds_a"] - df["tdb_a"] 859 | df["tdc"] = df.apply((lambda x: x["tdb_b"] % 9 if x["tdb_b"] > 9 else x["tdc"]), axis=1) 860 | df["tdc"] = df.apply((lambda x: (x["tds_b"] % 9) * -1 if x["tds_b"] > 9 else x["tdc"]), axis=1) 861 | dataframe.loc[:, "TD_count"] = df["tdc"] 862 | return dataframe 863 | 864 | 865 | def TKE(dataframe, *, length=14, emaperiod=5): 866 | """ 867 | Source: https://www.tradingview.com/script/Pcbvo0zG/ 868 | Author: Dr Yasar ERDINC 869 | 870 | The calculation is simple: 871 | TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 872 | Buy signal: when TKE crosses above 20 value 873 | Oversold region: under 20 value 874 | Overbought region: over 80 value 875 | 876 | Another usage of TKE is with its EMA , 877 | the default value is defined as 5 bars of EMA of the TKE line, 878 | Go long: when TKE crosses above EMALine 879 | Go short: when TKE crosses below EMALine 880 | 881 | Usage: 882 | `dataframe['TKE'], dataframe['TKEema'] = TKE1(dataframe)` 883 | """ 884 | import talib.abstract as ta 885 | 886 | df = dataframe.copy() 887 | # TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 888 | df["rsi"] = ta.RSI(df, timeperiod=length) 889 | df["stoch"] = ( 890 | 100 891 | * (df["close"] - df["low"].rolling(window=length).min()) 892 | / (df["high"].rolling(window=length).max() - df["low"].rolling(window=length).min()) 893 | ) 894 | 895 | df["ultosc"] = ta.ULTOSC(df, timeperiod1=7, timeperiod2=14, timeperiod3=28) 896 | df["mfi"] = ta.MFI(df, timeperiod=length) 897 | df["willr"] = ta.WILLR(df, timeperiod=length) 898 | df["mom"] = ta.ROCR100(df, timeperiod=length) 899 | df["cci"] = ta.CCI(df, timeperiod=length) 900 | df["TKE"] = df[["rsi", "stoch", "ultosc", "mfi", "willr", "mom", "cci"]].mean(axis="columns") 901 | df["TKEema"] = ta.EMA(df["TKE"], timeperiod=emaperiod) 902 | return df["TKE"], df["TKEema"] 903 | 904 | 905 | def vwmacd(dataframe, *, fastperiod=12, slowperiod=26, signalperiod=9): 906 | """ 907 | Volume Weighted MACD 908 | Author: KIVANC @fr3762 on twitter 909 | Developer: Buff Dormeier @BuffDormeierWFA on twitter 910 | Source: https://www.tradingview.com/script/wVe6AfGA 911 | 912 | study("VOLUME WEIGHTED MACD V2", shorttitle="VWMACDV2") 913 | fastperiod = input(12,title="fastperiod",type=integer,minval=1,maxval=500) 914 | slowperiod = input(26,title="slowperiod",type=integer,minval=1,maxval=500) 915 | signalperiod = input(9,title="signalperiod",type=integer,minval=1,maxval=500) 916 | fastMA = ema(volume*close, fastperiod)/ema(volume, fastperiod) 917 | slowMA = ema(volume*close, slowperiod)/ema(volume, slowperiod) 918 | vwmacd = fastMA - slowMA 919 | signal = ema(vwmacd, signalperiod) 920 | hist= vwmacd - signal 921 | plot(vwmacd, color=blue, linewidth=2) 922 | plot(signal, color=red, linewidth=2) 923 | plot(hist, color=green, linewidth=4, style=histogram) 924 | plot(0, color=black) 925 | 926 | Usage: 927 | vwmacd = vwmacd(dataframe) 928 | dataframe['vwmacd'] = vwmacd['vwmacd'] 929 | dataframe['vwmacdsignal'] = vwmacd['signal'] 930 | dataframe['vwmacdhist'] = vwmacd['hist'] 931 | # simplified: 932 | dataframe = vwmacd(dataframe) 933 | :returns: dataframe with new columns for vwmacd, signal and hist 934 | 935 | """ 936 | 937 | import talib.abstract as ta 938 | 939 | dataframe["fastMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], fastperiod) / ta.EMA( 940 | dataframe["volume"], fastperiod 941 | ) 942 | dataframe["slowMA"] = ta.EMA(dataframe["volume"] * dataframe["close"], slowperiod) / ta.EMA( 943 | dataframe["volume"], slowperiod 944 | ) 945 | dataframe["vwmacd"] = dataframe["fastMA"] - dataframe["slowMA"] 946 | dataframe["signal"] = ta.EMA(dataframe["vwmacd"], signalperiod) 947 | dataframe["hist"] = dataframe["vwmacd"] - dataframe["signal"] 948 | dataframe = dataframe.drop(["fastMA", "slowMA"], axis=1) 949 | return dataframe 950 | 951 | 952 | def RMI(dataframe, *, length=20, mom=5): 953 | """ 954 | Source: https://www.marketvolume.com/technicalanalysis/relativemomentumindex.asp 955 | length: Length of EMA 956 | mom: Momentum 957 | 958 | Usage: 959 | dataframe['RMI'] = RMI(dataframe) 960 | 961 | """ 962 | import talib.abstract as ta 963 | 964 | df = dataframe.copy() 965 | df["maxup"] = (df["close"] - df["close"].shift(mom)).clip(lower=0).fillna(0) 966 | df["maxdown"] = (df["close"].shift(mom) - df["close"]).clip(lower=0).fillna(0) 967 | 968 | df["emaInc"] = ta.EMA(df, price="maxup", timeperiod=length) 969 | df["emaDec"] = ta.EMA(df, price="maxdown", timeperiod=length) 970 | 971 | df["RMI"] = np.where(df["emaDec"] == 0, 0, 100 - 100 / (1 + df["emaInc"] / df["emaDec"])) 972 | return df["RMI"] 973 | 974 | 975 | def VIDYA(dataframe, length=9, select=True): 976 | """ 977 | Source: https://www.tradingview.com/script/64ynXU2e/ 978 | Author: Tushar Chande 979 | Pinescript Author: KivancOzbilgic 980 | 981 | Variable Index Dynamic Average VIDYA 982 | 983 | To achieve the goals, the indicator filters out the market fluctuations (noises) 984 | by averaging the price values of the periods, over which it is calculated. 985 | In the process, some extra value (weight) is added to the average prices, 986 | as it is done during calculations of all weighted indicators, such as EMA , LWMA, and SMMA. 987 | But during the VIDYA indicator's calculation, every period's price 988 | receives a weight increment adapted to the current market's volatility . 989 | 990 | select: True = CMO, False= StdDev as volatility index 991 | usage: 992 | dataframe['VIDYA'] = VIDYA(dataframe) 993 | """ 994 | df = dataframe.copy() 995 | alpha = 2 / (length + 1) 996 | df["momm"] = df["close"].diff() 997 | df["m1"] = np.where(df["momm"] >= 0, df["momm"], 0.0) 998 | df["m2"] = np.where(df["momm"] >= 0, 0.0, -df["momm"]) 999 | 1000 | df["sm1"] = df["m1"].rolling(length).sum() 1001 | df["sm2"] = df["m2"].rolling(length).sum() 1002 | 1003 | df["chandeMO"] = 100 * (df["sm1"] - df["sm2"]) / (df["sm1"] + df["sm2"]) 1004 | if select: 1005 | df["k"] = abs(df["chandeMO"]) / 100 1006 | else: 1007 | df["k"] = df["close"].rolling(length).std() 1008 | 1009 | cols = ["momm", "m1", "m2", "sm1", "sm2", "chandeMO", "k"] 1010 | df.loc[:, cols] = df.loc[:, cols].fillna(0.0) 1011 | 1012 | df["VIDYA"] = 0.0 1013 | for i in range(length, len(df)): 1014 | df["VIDYA"].iat[i] = ( 1015 | alpha * df["k"].iat[i] * df["close"].iat[i] 1016 | + (1 - alpha * df["k"].iat[i]) * df["VIDYA"].iat[i - 1] 1017 | ) 1018 | 1019 | return df["VIDYA"] 1020 | 1021 | 1022 | def MADR(dataframe, length=21, stds_dist=2, matype="sma"): 1023 | """ 1024 | Moving Average Deviation Rate, similar to bollinger bands 1025 | Source: https://tradingview.com/script/25KCgL9H/ 1026 | Author: tarantula3535 1027 | 1028 | Moving average deviation rate 1029 | 1030 | Simple moving average deviation rate and standard deviation. 1031 | 1032 | The bollinger band is momentum value standard deviation. 1033 | But the bollinger band is not normal distribution to close price. 1034 | Moving average deviation rate is normal distribution. 1035 | 1036 | This indicator will define upper and lower bounds based of stds-σ standard deviation of rate column. 1037 | If it exceeds stds-σ, it is a trading opportunity. 1038 | 1039 | """ 1040 | 1041 | import talib.abstract as ta 1042 | 1043 | df = dataframe.copy() 1044 | """ tradingview's code 1045 | _maPeriod = input(21, title="Moving average period") 1046 | 1047 | //deviation rate 1048 | _sma = sma(close, _maPeriod) 1049 | _rate = close / _sma * 100 - 100 1050 | 1051 | //deviation rate std 1052 | _stdCenter = sma(_rate, _maPeriod * 2) 1053 | _std = stdev(_rate, _maPeriod * 2) 1054 | _plusDev = _stdCenter + _std * 2 1055 | _minusDev = _stdCenter - _std * 2 1056 | """ 1057 | 1058 | if matype.lower() == "sma": 1059 | ma_close = ta.SMA(df, timeperiod=length) 1060 | elif matype.lower() == "ema": 1061 | ma_close = ta.EMA(df, timeperiod=length) 1062 | else: 1063 | ma_close = ta.SMA(df, timeperiod=length) 1064 | 1065 | df["rate"] = ((df["close"] / ma_close) * 100) - 100 1066 | 1067 | if matype.lower() == "sma": 1068 | df["stdcenter"] = ta.SMA(df.rate, timeperiod=(length * stds_dist)) 1069 | elif matype.lower() == "ema": 1070 | df["stdcenter"] = ta.EMA(df.rate, timeperiod=(length * stds_dist)) 1071 | else: 1072 | df["stdcenter"] = ta.SMA(df.rate, timeperiod=(length * stds_dist)) 1073 | 1074 | std = ta.STDDEV(df.rate, timeperiod=(length * stds_dist)) 1075 | df["plusdev"] = df["stdcenter"] + (std * stds_dist) 1076 | df["minusdev"] = df["stdcenter"] - (std * stds_dist) 1077 | # return stdcenter , plusdev , minusdev, rate 1078 | return df 1079 | 1080 | 1081 | def SSLChannels(dataframe, length=10, mode="sma"): 1082 | """ 1083 | Source: https://www.tradingview.com/script/xzIoaIJC-SSL-channel/ 1084 | Author: xmatthias 1085 | Pinescript Author: ErwinBeckers 1086 | 1087 | SSL Channels. 1088 | Average over highs and lows form a channel - lines "flip" when close crosses 1089 | either of the 2 lines. 1090 | Trading ideas: 1091 | * Channel cross 1092 | * as confirmation based on up > down for long 1093 | 1094 | Usage: 1095 | dataframe['sslDown'], dataframe['sslUp'] = SSLChannels(dataframe, 10) 1096 | """ 1097 | import talib.abstract as ta 1098 | 1099 | mode_lower = mode.lower() 1100 | 1101 | if mode_lower not in ("sma", "ema"): 1102 | raise ValueError(f"Mode {mode} not supported yet") 1103 | 1104 | df = dataframe.copy() 1105 | 1106 | if mode_lower == "sma": 1107 | ma_high = df["high"].rolling(length).mean() 1108 | ma_low = df["low"].rolling(length).mean() 1109 | elif mode_lower == "ema": 1110 | ma_high = ta.EMA(df["high"], length) 1111 | ma_low = ta.EMA(df["low"], length) 1112 | 1113 | df["hlv"] = np.where(df["close"] > ma_high, 1, np.where(df["close"] < ma_low, -1, np.nan)) 1114 | df["hlv"] = df["hlv"].ffill() 1115 | 1116 | df["sslDown"] = np.where(df["hlv"] < 0, ma_high, ma_low) 1117 | df["sslUp"] = np.where(df["hlv"] < 0, ma_low, ma_high) 1118 | 1119 | return df["sslDown"], df["sslUp"] 1120 | 1121 | 1122 | def PMAX(dataframe, period=10, multiplier=3, length=12, MAtype=1, src=1): # noqa: C901 1123 | """ 1124 | Function to compute PMAX 1125 | Source: https://www.tradingview.com/script/sU9molfV/ 1126 | Pinescript Author: KivancOzbilgic 1127 | 1128 | Args : 1129 | df : Pandas DataFrame with the columns ['date', 'open', 'high', 'low', 'close', 'volume'] 1130 | period : Integer indicates the period of computation in terms of number of candles 1131 | multiplier : Integer indicates value to multiply the ATR 1132 | length: moving averages length 1133 | MAtype: type of the moving average 1134 | 1135 | Returns : 1136 | df : Pandas DataFrame with new columns added for 1137 | ATR (ATR_$period) 1138 | PMAX (pm_$period_$multiplier_$length_$Matypeint) 1139 | PMAX Direction (pmX_$period_$multiplier_$length_$Matypeint) 1140 | """ 1141 | import talib.abstract as ta 1142 | 1143 | df = dataframe.copy() 1144 | mavalue = "MA_" + str(MAtype) + "_" + str(length) 1145 | atr = "ATR_" + str(period) 1146 | df[atr] = ta.ATR(df, timeperiod=period) 1147 | pm = "pm_" + str(period) + "_" + str(multiplier) + "_" + str(length) + "_" + str(MAtype) 1148 | pmx = "pmX_" + str(period) + "_" + str(multiplier) + "_" + str(length) + "_" + str(MAtype) 1149 | # MAtype==1 --> EMA 1150 | # MAtype==2 --> DEMA 1151 | # MAtype==3 --> T3 1152 | # MAtype==4 --> SMA 1153 | # MAtype==5 --> VIDYA 1154 | # MAtype==6 --> TEMA 1155 | # MAtype==7 --> WMA 1156 | # MAtype==8 --> VWMA 1157 | if src == 1: 1158 | masrc = df["close"] 1159 | elif src == 2: 1160 | masrc = (df["high"] + df["low"]) / 2 1161 | elif src == 3: 1162 | masrc = (df["high"] + df["low"] + df["close"] + df["open"]) / 4 1163 | if MAtype == 1: 1164 | df[mavalue] = ta.EMA(masrc, timeperiod=length) 1165 | elif MAtype in (2, 9): 1166 | # Compatibility for ZEMA (https://github.com/freqtrade/technical/pull/356 for details) 1167 | df[mavalue] = ta.DEMA(masrc, timeperiod=length) 1168 | elif MAtype == 3: 1169 | df[mavalue] = ta.T3(masrc, timeperiod=length) 1170 | elif MAtype == 4: 1171 | df[mavalue] = ta.SMA(masrc, timeperiod=length) 1172 | elif MAtype == 5: 1173 | df[mavalue] = VIDYA(df, length=length) 1174 | elif MAtype == 6: 1175 | df[mavalue] = ta.TEMA(masrc, timeperiod=length) 1176 | elif MAtype == 7: 1177 | df[mavalue] = ta.WMA(df, timeperiod=length) 1178 | elif MAtype == 8: 1179 | df[mavalue] = vwma(df, length) 1180 | else: 1181 | raise ValueError(f"MAtype {MAtype} not supported.") 1182 | # Compute basic upper and lower bands 1183 | df["basic_ub"] = df[mavalue] + (multiplier * df[atr]) 1184 | df["basic_lb"] = df[mavalue] - (multiplier * df[atr]) 1185 | # Compute final upper and lower bands 1186 | df["final_ub"] = 0.00 1187 | df["final_lb"] = 0.00 1188 | for i in range(period, len(df)): 1189 | df["final_ub"].iat[i] = ( 1190 | df["basic_ub"].iat[i] 1191 | if ( 1192 | df["basic_ub"].iat[i] < df["final_ub"].iat[i - 1] 1193 | or df[mavalue].iat[i - 1] > df["final_ub"].iat[i - 1] 1194 | ) 1195 | else df["final_ub"].iat[i - 1] 1196 | ) 1197 | df["final_lb"].iat[i] = ( 1198 | df["basic_lb"].iat[i] 1199 | if ( 1200 | df["basic_lb"].iat[i] > df["final_lb"].iat[i - 1] 1201 | or df[mavalue].iat[i - 1] < df["final_lb"].iat[i - 1] 1202 | ) 1203 | else df["final_lb"].iat[i - 1] 1204 | ) 1205 | 1206 | # Set the Pmax value 1207 | df[pm] = 0.00 1208 | for i in range(period, len(df)): 1209 | df[pm].iat[i] = ( 1210 | df["final_ub"].iat[i] 1211 | if ( 1212 | df[pm].iat[i - 1] == df["final_ub"].iat[i - 1] 1213 | and df[mavalue].iat[i] <= df["final_ub"].iat[i] 1214 | ) 1215 | else ( 1216 | df["final_lb"].iat[i] 1217 | if ( 1218 | df[pm].iat[i - 1] == df["final_ub"].iat[i - 1] 1219 | and df[mavalue].iat[i] > df["final_ub"].iat[i] 1220 | ) 1221 | else ( 1222 | df["final_lb"].iat[i] 1223 | if ( 1224 | df[pm].iat[i - 1] == df["final_lb"].iat[i - 1] 1225 | and df[mavalue].iat[i] >= df["final_lb"].iat[i] 1226 | ) 1227 | else ( 1228 | df["final_ub"].iat[i] 1229 | if ( 1230 | df[pm].iat[i - 1] == df["final_lb"].iat[i - 1] 1231 | and df[mavalue].iat[i] < df["final_lb"].iat[i] 1232 | ) 1233 | else 0.00 1234 | ) 1235 | ) 1236 | ) 1237 | ) 1238 | 1239 | # Mark the trend direction up/down 1240 | df[pmx] = np.where( 1241 | df[pm] > 0.00, 1242 | np.where(df[mavalue] < df[pm], "down", "up"), 1243 | "nan", 1244 | ) 1245 | # Remove basic and final bands from the columns 1246 | df.drop(["basic_ub", "basic_lb", "final_ub", "final_lb", mavalue], inplace=True, axis=1) 1247 | 1248 | cols = [pm, pmx, atr] 1249 | df.loc[:, cols] = df.loc[:, cols].fillna(0.0) 1250 | 1251 | return df 1252 | 1253 | 1254 | def tv_wma(dataframe: DataFrame, length: int = 9, field="close") -> Series: 1255 | """ 1256 | Source: Tradingview "Moving Average Weighted" 1257 | Pinescript Author: Unknown 1258 | 1259 | Args : 1260 | dataframe : Pandas Dataframe 1261 | length : WMA length 1262 | field : Field to use for the calculation 1263 | 1264 | Returns : 1265 | series : Pandas Series 1266 | """ 1267 | 1268 | if isinstance(dataframe, Series): 1269 | data = dataframe 1270 | else: 1271 | data = dataframe[field] 1272 | 1273 | norm = 0 1274 | sum = 0 1275 | 1276 | for i in range(1, length - 1): 1277 | weight = (length - i) * length 1278 | norm = norm + weight 1279 | sum = sum + data.shift(i) * weight 1280 | 1281 | tv_wma = sum / norm if (norm != 0) else 0 1282 | return tv_wma 1283 | 1284 | 1285 | def tv_hma(dataframe: DataFrame, length: int = 9, field="close") -> Series: 1286 | """ 1287 | Source: Tradingview "Hull Moving Average" 1288 | Pinescript Author: Unknown 1289 | 1290 | Args : 1291 | dataframe : Pandas Dataframe 1292 | length : HMA length 1293 | field : Field to use for the calculation 1294 | 1295 | Returns : 1296 | series : Pandas Series 1297 | """ 1298 | 1299 | if isinstance(dataframe, Series): 1300 | data = dataframe 1301 | else: 1302 | data = dataframe[field] 1303 | 1304 | h = 2 * tv_wma(data, math.floor(length / 2)) - tv_wma(data, length) 1305 | 1306 | tv_hma = tv_wma(h, math.floor(math.sqrt(length))) 1307 | 1308 | return tv_hma 1309 | 1310 | 1311 | def tv_alma( 1312 | dataframe: DataFrame, length: int = 8, offset: int = 0, sigma: int = 0, field="close" 1313 | ) -> Series: 1314 | """ 1315 | Source: Tradingview "Arnaud Legoux Moving Average" 1316 | Links: https://www.tradingview.com/pine-script-reference/v5/#fun_ta.alma 1317 | https://www.tradingview.com/support/solutions/43000594683/ 1318 | Pinescript Author: Arnaud Legoux and Dimitrios Douzis-Loukas 1319 | Description: Gaussian distribution that is shifted with 1320 | a calculated offset in order for 1321 | the average to be biased towards 1322 | more recent days, instead of more 1323 | evenly centered on the window. 1324 | 1325 | Args : 1326 | dataframe : Pandas Dataframe 1327 | length : ALMA windowframe 1328 | offset : Shift 1329 | sigma : Gaussian Smoothing 1330 | field : Field to use for the calculation 1331 | 1332 | Returns : 1333 | series : Series of ALMA values 1334 | """ 1335 | 1336 | """ This is simple computation way, just for reference """ 1337 | # sigma = sigma or 1e-10 1338 | # m = offset * (length - 1) 1339 | # s = length / sigma 1340 | # norm = 0.0 1341 | # sum = 0.0 1342 | # for i in range(length - 1): 1343 | # weight = np.exp(-1 * np.power(i - m, 2) / (2 * np.power(s, 2))) 1344 | # norm += weight 1345 | # sum += dataframe[field].shift(length - i - 1) * weight 1346 | # return sum / norm 1347 | 1348 | """ Vectorized method """ 1349 | sigma = sigma or 1e-10 1350 | 1351 | m = offset * (length - 1) 1352 | s = length / sigma 1353 | 1354 | indices = np.arange(length) 1355 | weights = np.exp(-np.power(indices - m, 2) / (2 * np.power(s, 2))) 1356 | weights /= weights.sum() # Normalize the weights 1357 | 1358 | alma = np.convolve(dataframe[field], weights[::-1], mode="valid") 1359 | return Series(np.pad(alma, (length - 1, 0), mode="constant", constant_values=np.nan)) 1360 | 1361 | 1362 | def tv_trama(dataframe: DataFrame, length: int = 99, field="close") -> Series: 1363 | """ 1364 | Name : Tradingview "Trend Regularity Adaptive Moving Average" 1365 | Pinescript Author : LuxAlgo 1366 | Link : 1367 | tradingview.com/script/p8wGCPi6-Trend-Regularity-Adaptive-Moving-Average-LuxAlgo/ 1368 | 1369 | Args : 1370 | dataframe : Pandas Dataframe 1371 | length : Period of the indicator 1372 | field : Field to use for the calculation 1373 | 1374 | Returns : 1375 | series : 'TRAMA' values 1376 | """ 1377 | 1378 | import talib.abstract as ta 1379 | 1380 | df_len = len(dataframe) 1381 | 1382 | hh = ta.MAX(dataframe["high"], length) 1383 | ll = ta.MIN(dataframe["low"], length) 1384 | hh_or_ll = np.where(np.diff(hh) > 0, 1, 0) + np.where(np.diff(ll) < 0, 1, 0) 1385 | 1386 | tc = np.zeros(df_len) 1387 | tc[:-1] = np.nan_to_num(ta.SMA(hh_or_ll.astype(float), length) ** 2) 1388 | 1389 | ama = np.zeros(df_len) 1390 | ama[0] = dataframe[field].iloc[0] 1391 | for i in range(1, df_len): 1392 | ama[i] = ama[i - 1] + tc[i - 1] * (dataframe[field].iloc[i] - ama[i - 1]) 1393 | 1394 | return Series(ama) 1395 | -------------------------------------------------------------------------------- /technical/indicators/momentum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Momentum indicators 3 | """ 4 | 5 | ######################################## 6 | # 7 | # Momentum Indicator Functions 8 | # 9 | 10 | # ADX Average Directional Movement Index 11 | # ADXR Average Directional Movement Index Rating 12 | # APO Absolute Price Oscillator 13 | # AROON Aroon 14 | # AROONOSC Aroon Oscillator 15 | # BOP Balance Of Power 16 | 17 | # CCI Commodity Channel Index 18 | 19 | # CMO Chande Momentum Oscillator 20 | 21 | # DX Directional Movement Index 22 | # MACD Moving Average Convergence/Divergence 23 | # MACDEXT MACD with controllable MA type 24 | # MACDFIX Moving Average Convergence/Divergence Fix 12/26 25 | # MFI Money Flow Index 26 | # MINUS_DI Minus Directional Indicator 27 | # MINUS_DM Minus Directional Movement 28 | 29 | # MOM Momentum 30 | 31 | # PLUS_DI Plus Directional Indicator 32 | # PLUS_DM Plus Directional Movement 33 | # PPO Percentage Price Oscillator 34 | # ROC Rate of change : ((price/prevPrice)-1)*100 35 | # ROCP Rate of change Percentage: (price-prevPrice)/prevPrice 36 | # ROCR Rate of change ratio: (price/prevPrice) 37 | # ROCR100 Rate of change ratio 100 scale: (price/prevPrice)*100 38 | # RSI Relative Strength Index 39 | # STOCH Stochastic 40 | # STOCHF Stochastic Fast 41 | # STOCHRSI Stochastic Relative Strength Index 42 | # TRIX 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA 43 | 44 | # ULTOSC Ultimate Oscillator 45 | 46 | 47 | # WILLR Williams' %R 48 | def williams_percent(dataframe, period=14): 49 | highest_high = dataframe["high"].rolling(period).max() 50 | lowest_low = dataframe["low"].rolling(period).min() 51 | wr = (highest_high - dataframe["close"]) / (highest_high - lowest_low) * -100 52 | return wr 53 | -------------------------------------------------------------------------------- /technical/indicators/overlap_studies.py: -------------------------------------------------------------------------------- 1 | """ 2 | Overlap studies 3 | """ 4 | 5 | import talib.abstract as ta 6 | from numpy import ndarray 7 | from pandas import DataFrame, Series 8 | 9 | ######################################## 10 | # 11 | # Overlap Studies Functions 12 | # 13 | 14 | 15 | # BBANDS Bollinger Bands 16 | def bollinger_bands( 17 | dataframe: DataFrame, 18 | period: int = 21, 19 | stdv: int = 2, 20 | field: str = "close", 21 | colum_prefix: str = "bb", 22 | ma_type: str = "sma", 23 | ) -> DataFrame: 24 | """ 25 | Bollinger bands, using Moving Average. 26 | Copying original dataframe and returns dataframe with the following 3 columns 27 | _lower, _middle, and _upper, 28 | """ 29 | 30 | df = dataframe.copy() 31 | 32 | if ma_type.lower() == "sma": 33 | ma = ta.SMA(df[field], period) 34 | elif ma_type.lower() == "ema": 35 | ma = ta.EMA(df[field], period) 36 | elif ma_type.lower() == "dema": 37 | ma = ta.DEMA(df[field], period) 38 | elif ma_type.lower() == "tema": 39 | ma = ta.TEMA(df[field], period) 40 | else: 41 | ma = ta.SMA(df[field], period) 42 | 43 | std = df[field].rolling(period).std() 44 | upper = ma + (std * stdv) 45 | lower = ma - (std * stdv) 46 | 47 | df[f"{colum_prefix}_lower"] = lower 48 | df[f"{colum_prefix}_middle"] = ma 49 | df[f"{colum_prefix}_upper"] = upper 50 | 51 | return df 52 | 53 | 54 | # DEMA Double Exponential Moving Average 55 | def dema(dataframe, period, field="close"): 56 | import talib.abstract as ta 57 | 58 | return ta.DEMA(dataframe, timeperiod=period, price=field) 59 | 60 | 61 | def zema(dataframe, period, field="close"): 62 | """ 63 | Compatibility alias for Zema 64 | https://github.com/freqtrade/technical/pull/356 for details. 65 | Please migrate to dema instead. 66 | Raises a Future warning - will be removed in a future version. 67 | """ 68 | import warnings 69 | 70 | warnings.warn("zema is deprecated, use dema instead", FutureWarning) 71 | 72 | return dema(dataframe, period, field) 73 | 74 | 75 | # EMA Exponential Moving Average 76 | def ema(dataframe: DataFrame, period: int, field="close") -> Series: 77 | """ 78 | Wrapper around talib ema (using the abstract interface) 79 | """ 80 | import talib.abstract as ta 81 | 82 | return ta.EMA(dataframe, timeperiod=period, price=field) 83 | 84 | 85 | # HT_TRENDLINE Hilbert Transform - Instantaneous Trendline 86 | # KAMA Kaufman Adaptive Moving Average 87 | # MA Moving average 88 | # MAMA MESA Adaptive Moving Average 89 | # MAVP Moving average with variable period 90 | # MIDPOINT MidPoint over period 91 | # MIDPRICE Midpoint Price over period 92 | # SAR Parabolic SAR 93 | # SAREXT Parabolic SAR - Extended 94 | 95 | 96 | # SMA Simple Moving Average 97 | def sma(dataframe, period, field="close"): 98 | import talib.abstract as ta 99 | 100 | return ta.SMA(dataframe, timeperiod=period, price=field) 101 | 102 | 103 | # T3 Triple Exponential Moving Average (T3) 104 | 105 | 106 | # TEMA Triple Exponential Moving Average 107 | def tema(dataframe, period, field="close"): 108 | import talib.abstract as ta 109 | 110 | return ta.TEMA(dataframe, timeperiod=period, price=field) 111 | 112 | 113 | # TRIMA Triangular Moving Average 114 | # WMA Weighted Moving Average 115 | 116 | 117 | # Other Overlap Studies Functions 118 | def hull_moving_average(dataframe, period, field="close") -> ndarray: 119 | # TODO: Remove this helper method, it's a 1:1 call to qtpylib's HMA. 120 | from technical.qtpylib import hma 121 | 122 | return hma(dataframe[field], period) 123 | 124 | 125 | def vwma(df, window, price="close"): 126 | return (df[price] * df["volume"]).rolling(window).sum() / df.volume.rolling(window).sum() 127 | -------------------------------------------------------------------------------- /technical/indicators/price_transform.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cycle indicators 3 | """ 4 | 5 | ######################################## 6 | # 7 | # Price Transform Functions 8 | # 9 | 10 | # AVGPRICE Average Price 11 | # MEDPRICE Median Price 12 | # TYPPRICE Typical Price 13 | # WCLPRICE Weighted Close Price 14 | -------------------------------------------------------------------------------- /technical/indicators/volatility.py: -------------------------------------------------------------------------------- 1 | """ 2 | Volatility indicator functions 3 | """ 4 | 5 | import numpy as np 6 | import pandas as pd 7 | from numpy import ndarray 8 | 9 | from technical.vendor.qtpylib.indicators import atr # noqa: F401 10 | 11 | ######################################## 12 | # 13 | # Volatility Indicator Functions 14 | # 15 | 16 | ######################################## 17 | # 18 | # ATR Average True Range 19 | # Imported from qtpylib, which is a fast implementation. 20 | 21 | 22 | def atr_percent(dataframe, period: int = 14) -> ndarray: 23 | """ 24 | 25 | :param dataframe: Dataframe containing candle data 26 | :param period: Period to use for ATR calculation (defaults to 14) 27 | :return: Series containing ATR_percent calculation 28 | """ 29 | return (atr(dataframe, period) / dataframe["close"]) * 100 30 | 31 | 32 | # NATR Normalized Average True Range 33 | # TRANGE True Range 34 | 35 | ######################################## 36 | 37 | 38 | def chopiness(dataframe, period: int = 14): 39 | """ 40 | Choppiness index 41 | theory https://www.tradingview.com/scripts/choppinessindex/ 42 | slightly adapted from 43 | https://medium.com/codex/detecting-ranging-and-trending-markets-with-choppiness-index-in-python-1942e6450b58 44 | 45 | :param dataframe: Dataframe containing candle data 46 | :param period: Period to use for chopiness calculation (defaults to 14) 47 | :return: Series containing chopiness calculation :values 0 to +100 48 | """ 49 | 50 | tr1 = dataframe["high"] - dataframe["low"] 51 | tr2 = abs(dataframe["high"] - dataframe["close"].shift(1)) 52 | tr3 = abs(dataframe["low"] - dataframe["close"].shift(1)) 53 | 54 | tr = pd.concat([tr1, tr2, tr3], axis=1, join="inner").dropna().max(axis=1) 55 | atr = tr.rolling(1).mean() 56 | highh = dataframe["high"].rolling(period).max() 57 | lowl = dataframe["low"].rolling(period).min() 58 | ci = 100 * np.log10((atr.rolling(period).sum()) / (highh - lowl)) / np.log10(period) 59 | return ci 60 | -------------------------------------------------------------------------------- /technical/indicators/volume_indicators.py: -------------------------------------------------------------------------------- 1 | """ 2 | Volume indicators 3 | """ 4 | 5 | ######################################## 6 | # 7 | # Volume Indicator Functions 8 | # 9 | 10 | # AD Chaikin A/D Line 11 | 12 | # ADOSC Chaikin A/D Oscillator 13 | # OBV On Balance Volume 14 | 15 | 16 | # Other Volume Indicator Functions 17 | def chaikin_money_flow(dataframe, period=21): 18 | mfm = (dataframe["close"] - dataframe["low"]) - (dataframe["high"] - dataframe["close"]) / ( 19 | dataframe["high"] - dataframe["low"] 20 | ) 21 | mfv = mfm * dataframe["volume"] 22 | cmf = mfv.rolling(period).sum() / dataframe["volume"].rolling(period).sum() 23 | return cmf 24 | 25 | 26 | cmf = chaikin_money_flow 27 | -------------------------------------------------------------------------------- /technical/pivots_points.py: -------------------------------------------------------------------------------- 1 | import freqtrade.vendor.qtpylib.indicators as qtpylib 2 | import pandas as pd 3 | 4 | """ 5 | Indicators for Freqtrade 6 | author@: Gerald Lonlas 7 | """ 8 | 9 | 10 | def pivots_points(dataframe: pd.DataFrame, timeperiod=30, levels=3) -> pd.DataFrame: 11 | """ 12 | Pivots Points 13 | 14 | https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/ 15 | 16 | Formula: 17 | Pivot = (Previous High + Previous Low + Previous Close)/3 18 | 19 | Resistance #1 = (2 x Pivot) - Previous Low 20 | Support #1 = (2 x Pivot) - Previous High 21 | 22 | Resistance #2 = (Pivot - Support #1) + Resistance #1 23 | Support #2 = Pivot - (Resistance #1 - Support #1) 24 | 25 | Resistance #3 = (Pivot - Support #2) + Resistance #2 26 | Support #3 = Pivot - (Resistance #2 - Support #2) 27 | ... 28 | 29 | :param dataframe: 30 | :param timeperiod: Period to compare (in ticker) 31 | :param levels: Num of support/resistance desired 32 | :return: dataframe 33 | """ 34 | 35 | data = {} 36 | 37 | low = qtpylib.rolling_mean( 38 | series=pd.Series(index=dataframe.index, data=dataframe["low"]), window=timeperiod 39 | ) 40 | 41 | high = qtpylib.rolling_mean( 42 | series=pd.Series(index=dataframe.index, data=dataframe["high"]), window=timeperiod 43 | ) 44 | 45 | # Pivot 46 | data["pivot"] = qtpylib.rolling_mean(series=qtpylib.typical_price(dataframe), window=timeperiod) 47 | 48 | # Resistance #1 49 | data["r1"] = (2 * data["pivot"]) - low 50 | 51 | # Resistance #2 52 | data["s1"] = (2 * data["pivot"]) - high 53 | 54 | # Calculate Resistances and Supports >1 55 | for i in range(2, levels + 1): 56 | prev_support = data["s" + str(i - 1)] 57 | prev_resistance = data["r" + str(i - 1)] 58 | 59 | # Resistance 60 | data["r" + str(i)] = (data["pivot"] - prev_support) + prev_resistance 61 | 62 | # Support 63 | data["s" + str(i)] = data["pivot"] - (prev_resistance - prev_support) 64 | 65 | return pd.DataFrame(index=dataframe.index, data=data) 66 | -------------------------------------------------------------------------------- /technical/qtpylib.py: -------------------------------------------------------------------------------- 1 | # Import here for easy access 2 | # Keep the original file in vendor to make the origin clear 3 | from technical.vendor.qtpylib.indicators import * # noqa 4 | -------------------------------------------------------------------------------- /technical/trendline.py: -------------------------------------------------------------------------------- 1 | """ 2 | defines trendline based indicator logic 3 | based on 4 | https://github.com/dysonance/Trendy 5 | """ 6 | 7 | 8 | def gentrends(dataframe, field="close", window=1 / 3.0, charts=False): 9 | """ 10 | Returns a Pandas dataframe with support and resistance lines. 11 | 12 | :param dataframe: incoming data matrix 13 | :param field: for which column would you like to generate the trendline 14 | :param window: How long the trendlines should be. If window < 1, then it 15 | will be taken as a percentage of the size of the data 16 | :param charts: Boolean value saying whether to print chart to screen 17 | """ 18 | 19 | x = dataframe[field] 20 | 21 | import numpy as np 22 | import pandas as pd 23 | 24 | x = np.array(x) 25 | 26 | if window < 1: 27 | window = int(window * len(x)) 28 | 29 | max1 = np.where(x == max(x))[0][0] # find the index of the abs max 30 | min1 = np.where(x == min(x))[0][0] # find the index of the abs min 31 | 32 | # First the max 33 | if max1 + window >= len(x): 34 | max2 = max(x[0 : (max1 - window)]) 35 | else: 36 | max2 = max(x[(max1 + window) :]) 37 | 38 | # Now the min 39 | if min1 - window <= 0: 40 | min2 = min(x[(min1 + window) :]) 41 | else: 42 | min2 = min(x[0 : (min1 - window)]) 43 | 44 | # Now find the indices of the secondary extrema 45 | max2 = np.where(x == max2)[0][0] # find the index of the 2nd max 46 | min2 = np.where(x == min2)[0][0] # find the index of the 2nd min 47 | 48 | # Create & extend the lines 49 | maxslope = (x[max1] - x[max2]) / (max1 - max2) # slope between max points 50 | minslope = (x[min1] - x[min2]) / (min1 - min2) # slope between min points 51 | a_max = x[max1] - (maxslope * max1) # y-intercept for max trendline 52 | a_min = x[min1] - (minslope * min1) # y-intercept for min trendline 53 | b_max = x[max1] + (maxslope * (len(x) - max1)) # extend to last data pt 54 | b_min = x[min1] + (minslope * (len(x) - min1)) # extend to last data point 55 | maxline = np.linspace(a_max, b_max, len(x)) # Y values between max's 56 | minline = np.linspace(a_min, b_min, len(x)) # Y values between min's 57 | 58 | # OUTPUT 59 | trends = np.transpose(np.array((x, maxline, minline))) 60 | trends = pd.DataFrame( 61 | trends, index=np.arange(0, len(x)), columns=["Data", "Max Line", "Min Line"] 62 | ) 63 | 64 | if charts: 65 | from matplotlib.pyplot import close, grid, plot, savefig 66 | 67 | plot(trends) 68 | grid() 69 | 70 | if isinstance(charts, str): 71 | savefig(f"{charts}.png") 72 | else: 73 | savefig(f"{x[0]}_{x[len(x) - 1]}.png") 74 | close() 75 | 76 | return trends 77 | 78 | 79 | def segtrends(dataframe, field="close", segments=2, charts=False): 80 | """ 81 | Turn minitrends to iterative process more easily adaptable to 82 | implementation in simple trading systems; allows backtesting functionality. 83 | 84 | :param dataframe: incoming data matrix 85 | :param field: for which column would you like to generate the trendline 86 | :param segments: Number of Trend line segments to generate 87 | :param charts: Boolean value saying whether to print chart to screen 88 | """ 89 | 90 | x = dataframe[field] 91 | import numpy as np 92 | 93 | y = np.array(x) 94 | 95 | # Implement trendlines 96 | segments = int(segments) 97 | maxima = np.ones(segments) 98 | minima = np.ones(segments) 99 | segsize = int(len(y) / segments) 100 | for i in range(1, segments + 1): 101 | ind2 = i * segsize 102 | ind1 = ind2 - segsize 103 | maxima[i - 1] = max(y[ind1:ind2]) 104 | minima[i - 1] = min(y[ind1:ind2]) 105 | 106 | # Find the indexes of these maxima in the data 107 | x_maxima = np.ones(segments) 108 | x_minima = np.ones(segments) 109 | for i in range(0, segments): 110 | x_maxima[i] = np.where(y == maxima[i])[0][0] 111 | x_minima[i] = np.where(y == minima[i])[0][0] 112 | 113 | if charts: 114 | import matplotlib.pyplot as plt 115 | 116 | plt.plot(y) 117 | plt.grid(True) 118 | 119 | for i in range(0, segments - 1): 120 | maxslope = (maxima[i + 1] - maxima[i]) / (x_maxima[i + 1] - x_maxima[i]) 121 | a_max = maxima[i] - (maxslope * x_maxima[i]) 122 | b_max = maxima[i] + (maxslope * (len(y) - x_maxima[i])) 123 | maxline = np.linspace(a_max, b_max, len(y)) 124 | 125 | minslope = (minima[i + 1] - minima[i]) / (x_minima[i + 1] - x_minima[i]) 126 | a_min = minima[i] - (minslope * x_minima[i]) 127 | b_min = minima[i] + (minslope * (len(y) - x_minima[i])) 128 | minline = np.linspace(a_min, b_min, len(y)) 129 | 130 | if charts: 131 | plt.plot(maxline, "g") 132 | plt.plot(minline, "r") 133 | 134 | if charts: 135 | plt.show() 136 | 137 | import pandas as pd 138 | 139 | # OUTPUT 140 | # return x_maxima, maxima, x_minima, minima 141 | trends = np.transpose(np.array((x, maxline, minline))) 142 | trends = pd.DataFrame( 143 | trends, index=np.arange(0, len(x)), columns=["Data", "Max Line", "Min Line"] 144 | ) 145 | return trends 146 | -------------------------------------------------------------------------------- /technical/util.py: -------------------------------------------------------------------------------- 1 | """ 2 | defines utility functions to be used 3 | """ 4 | 5 | from pandas import DataFrame, DatetimeIndex, merge, to_datetime, to_timedelta 6 | 7 | TICKER_INTERVAL_MINUTES = { 8 | "1m": 1, 9 | "5m": 5, 10 | "15m": 15, 11 | "30m": 30, 12 | "1h": 60, 13 | "60m": 60, 14 | "2h": 120, 15 | "4h": 240, 16 | "6h": 360, 17 | "12h": 720, 18 | "1d": 1440, 19 | "1w": 10080, 20 | } 21 | 22 | 23 | def ticker_history_to_dataframe(ticker: list) -> DataFrame: 24 | """ 25 | builds a dataframe based on the given ticker history 26 | 27 | :param ticker: See exchange.get_ticker_history 28 | :return: DataFrame 29 | """ 30 | cols = ["date", "open", "high", "low", "close", "volume"] 31 | frame = DataFrame(ticker, columns=cols) 32 | 33 | frame["date"] = to_datetime(frame["date"], unit="ms", utc=True) 34 | 35 | # group by index and aggregate results to eliminate duplicate ticks 36 | frame = frame.groupby(by="date", as_index=False, sort=True).agg( 37 | { 38 | "open": "first", 39 | "high": "max", 40 | "low": "min", 41 | "close": "last", 42 | "volume": "max", 43 | } 44 | ) 45 | frame.drop(frame.tail(1).index, inplace=True) # eliminate partial candle 46 | return frame 47 | 48 | 49 | def resample_to_interval(dataframe: DataFrame, interval): 50 | """ 51 | Resamples the given dataframe to the desired interval. 52 | Please be aware you need to use resampled_merge to merge to another dataframe to 53 | avoid lookahead bias 54 | 55 | :param dataframe: dataframe containing close/high/low/open/volume 56 | :param interval: to which ticker value in minutes would you like to resample it 57 | :return: 58 | """ 59 | if isinstance(interval, str): 60 | interval = TICKER_INTERVAL_MINUTES[interval] 61 | 62 | df = dataframe.copy() 63 | df = df.set_index(DatetimeIndex(df["date"])) 64 | ohlc_dict = {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"} 65 | # Resample to "left" border as dates are candle open dates 66 | df = df.resample(str(interval) + "min", label="left").agg(ohlc_dict).dropna() 67 | df.reset_index(inplace=True) 68 | 69 | return df 70 | 71 | 72 | def resampled_merge(original: DataFrame, resampled: DataFrame, fill_na=True): 73 | """ 74 | Merges a resampled dataset back into the original data set. 75 | Resampled candle will match OHLC only if full timespan is available in original dataframe. 76 | 77 | :param original: the original non resampled dataset 78 | :param resampled: the resampled dataset 79 | :return: the merged dataset 80 | """ 81 | 82 | original_int = compute_interval(original) 83 | resampled_int = compute_interval(resampled) 84 | 85 | if original_int < resampled_int: 86 | # Subtract "small" timeframe so merging is not delayed by 1 small candle. 87 | # Detailed explanation in https://github.com/freqtrade/freqtrade/issues/4073 88 | resampled["date_merge"] = ( 89 | resampled["date"] + to_timedelta(resampled_int, "m") - to_timedelta(original_int, "m") 90 | ) 91 | else: 92 | raise ValueError( 93 | "Tried to merge a faster timeframe to a slower timeframe. Upsampling is not possible." 94 | ) 95 | 96 | # rename all the columns to the correct interval 97 | resampled.columns = [f"resample_{resampled_int}_{col}" for col in resampled.columns] 98 | 99 | dataframe = merge( 100 | original, 101 | resampled, 102 | how="left", 103 | left_on="date", 104 | right_on=f"resample_{resampled_int}_date_merge", 105 | ) 106 | dataframe = dataframe.drop(f"resample_{resampled_int}_date_merge", axis=1) 107 | 108 | if fill_na: 109 | dataframe = dataframe.ffill() 110 | 111 | return dataframe 112 | 113 | 114 | def compute_interval(dataframe: DataFrame, exchange_interval=False): 115 | """ 116 | Calculates the interval of the given dataframe for us 117 | :param dataframe: 118 | :param exchange_interval: should we convert the result to an exchange interval or just a number 119 | :return: 120 | """ 121 | res_interval = int((dataframe["date"] - dataframe["date"].shift()).min().total_seconds() // 60) 122 | 123 | if exchange_interval: 124 | # convert to our allowed ticker values 125 | converted = list(TICKER_INTERVAL_MINUTES.keys())[ 126 | list(TICKER_INTERVAL_MINUTES.values()).index(res_interval) 127 | ] 128 | if len(converted) > 0: 129 | return converted 130 | else: 131 | raise Exception( 132 | f"sorry, your interval of {res_interval} is not " 133 | f"supported in {TICKER_INTERVAL_MINUTES}" 134 | ) 135 | 136 | return res_interval 137 | -------------------------------------------------------------------------------- /technical/vendor/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/technical/vendor/__init__.py -------------------------------------------------------------------------------- /technical/vendor/qtpylib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/technical/vendor/qtpylib/__init__.py -------------------------------------------------------------------------------- /technical/vendor/qtpylib/indicators.py: -------------------------------------------------------------------------------- 1 | # QTPyLib: Quantitative Trading Python Library 2 | # https://github.com/ranaroussi/qtpylib 3 | # 4 | # Copyright 2016-2018 Ran Aroussi 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | import warnings 20 | from datetime import datetime, timedelta 21 | 22 | import numpy as np 23 | import pandas as pd 24 | from pandas.core.base import PandasObject 25 | 26 | # ============================================= 27 | warnings.simplefilter(action="ignore", category=RuntimeWarning) 28 | 29 | # ============================================= 30 | 31 | 32 | def numpy_rolling_window(data, window): 33 | shape = data.shape[:-1] + (data.shape[-1] - window + 1, window) 34 | strides = data.strides + (data.strides[-1],) 35 | return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides) 36 | 37 | 38 | def numpy_rolling_series(func): 39 | def func_wrapper(data, window, as_source=False): 40 | series = data.values if isinstance(data, pd.Series) else data 41 | 42 | new_series = np.empty(len(series)) * np.nan 43 | calculated = func(series, window) 44 | new_series[-len(calculated) :] = calculated 45 | 46 | if as_source and isinstance(data, pd.Series): 47 | return pd.Series(index=data.index, data=new_series) 48 | 49 | return new_series 50 | 51 | return func_wrapper 52 | 53 | 54 | @numpy_rolling_series 55 | def numpy_rolling_mean(data, window, as_source=False): 56 | return np.mean(numpy_rolling_window(data, window), axis=-1) 57 | 58 | 59 | @numpy_rolling_series 60 | def numpy_rolling_std(data, window, as_source=False): 61 | return np.std(numpy_rolling_window(data, window), axis=-1, ddof=1) 62 | 63 | 64 | # --------------------------------------------- 65 | 66 | 67 | def session(df, start="17:00", end="16:00"): 68 | """remove previous globex day from df""" 69 | if df.empty: 70 | return df 71 | 72 | # get start/end/now as decimals 73 | int_start = list(map(int, start.split(":"))) 74 | int_start = (int_start[0] + int_start[1] - 1 / 100) - 0.0001 75 | int_end = list(map(int, end.split(":"))) 76 | int_end = int_end[0] + int_end[1] / 100 77 | int_now = df[-1:].index.hour[0] + (df[:1].index.minute[0]) / 100 78 | 79 | # same-dat session? 80 | is_same_day = int_end > int_start 81 | 82 | # set pointers 83 | curr = prev = df[-1:].index[0].strftime("%Y-%m-%d") 84 | 85 | # globex/forex session 86 | if not is_same_day: 87 | prev = (datetime.strptime(curr, "%Y-%m-%d") - timedelta(1)).strftime("%Y-%m-%d") 88 | 89 | # slice 90 | if int_now >= int_start: 91 | df = df[df.index >= curr + " " + start] 92 | else: 93 | df = df[df.index >= prev + " " + start] 94 | 95 | return df.copy() 96 | 97 | 98 | # --------------------------------------------- 99 | 100 | 101 | def heikinashi(bars): 102 | bars = bars.copy() 103 | bars["ha_close"] = (bars["open"] + bars["high"] + bars["low"] + bars["close"]) / 4 104 | 105 | # ha open 106 | bars.at[0, "ha_open"] = (bars.at[0, "open"] + bars.at[0, "close"]) / 2 107 | for i in range(1, len(bars)): 108 | bars.at[i, "ha_open"] = (bars.at[i - 1, "ha_open"] + bars.at[i - 1, "ha_close"]) / 2 109 | 110 | bars["ha_high"] = bars.loc[:, ["high", "ha_open", "ha_close"]].max(axis=1) 111 | bars["ha_low"] = bars.loc[:, ["low", "ha_open", "ha_close"]].min(axis=1) 112 | 113 | return pd.DataFrame( 114 | index=bars.index, 115 | data={ 116 | "open": bars["ha_open"], 117 | "high": bars["ha_high"], 118 | "low": bars["ha_low"], 119 | "close": bars["ha_close"], 120 | }, 121 | ) 122 | 123 | 124 | # --------------------------------------------- 125 | 126 | 127 | def tdi(series, rsi_lookback=13, rsi_smooth_len=2, rsi_signal_len=7, bb_lookback=34, bb_std=1.6185): 128 | rsi_data = rsi(series, rsi_lookback) 129 | rsi_smooth = sma(rsi_data, rsi_smooth_len) 130 | rsi_signal = sma(rsi_data, rsi_signal_len) 131 | 132 | bb_series = bollinger_bands(rsi_data, bb_lookback, bb_std) 133 | 134 | return pd.DataFrame( 135 | index=series.index, 136 | data={ 137 | "rsi": rsi_data, 138 | "rsi_signal": rsi_signal, 139 | "rsi_smooth": rsi_smooth, 140 | "rsi_bb_upper": bb_series["upper"], 141 | "rsi_bb_lower": bb_series["lower"], 142 | "rsi_bb_mid": bb_series["mid"], 143 | }, 144 | ) 145 | 146 | 147 | # --------------------------------------------- 148 | 149 | 150 | def awesome_oscillator(df, weighted=False, fast=5, slow=34): 151 | midprice = (df["high"] + df["low"]) / 2 152 | 153 | if weighted: 154 | ao = (midprice.ewm(fast).mean() - midprice.ewm(slow).mean()).values 155 | else: 156 | ao = numpy_rolling_mean(midprice, fast) - numpy_rolling_mean(midprice, slow) 157 | 158 | return pd.Series(index=df.index, data=ao) 159 | 160 | 161 | # --------------------------------------------- 162 | 163 | 164 | def nans(length=1): 165 | mtx = np.empty(length) 166 | mtx[:] = np.nan 167 | return mtx 168 | 169 | 170 | # --------------------------------------------- 171 | 172 | 173 | def typical_price(bars): 174 | res = (bars["high"] + bars["low"] + bars["close"]) / 3.0 175 | return pd.Series(index=bars.index, data=res) 176 | 177 | 178 | # --------------------------------------------- 179 | 180 | 181 | def mid_price(bars): 182 | res = (bars["high"] + bars["low"]) / 2.0 183 | return pd.Series(index=bars.index, data=res) 184 | 185 | 186 | # --------------------------------------------- 187 | 188 | 189 | def ibs(bars): 190 | """Internal bar strength""" 191 | res = np.round((bars["close"] - bars["low"]) / (bars["high"] - bars["low"]), 2) 192 | return pd.Series(index=bars.index, data=res) 193 | 194 | 195 | # --------------------------------------------- 196 | 197 | 198 | def true_range(bars): 199 | return pd.DataFrame( 200 | { 201 | "hl": bars["high"] - bars["low"], 202 | "hc": abs(bars["high"] - bars["close"].shift(1)), 203 | "lc": abs(bars["low"] - bars["close"].shift(1)), 204 | } 205 | ).max(axis=1) 206 | 207 | 208 | # --------------------------------------------- 209 | 210 | 211 | def atr(bars, window=14, exp=False): 212 | tr = true_range(bars) 213 | 214 | if exp: 215 | res = rolling_weighted_mean(tr, window) 216 | else: 217 | res = rolling_mean(tr, window) 218 | 219 | return pd.Series(res) 220 | 221 | 222 | # --------------------------------------------- 223 | 224 | 225 | def crossed(series1, series2, direction=None): 226 | if isinstance(series1, np.ndarray): 227 | series1 = pd.Series(series1) 228 | 229 | if isinstance(series2, (float, int, np.ndarray, np.integer, np.floating)): 230 | series2 = pd.Series(index=series1.index, data=series2) 231 | 232 | if direction is None or direction == "above": 233 | above = pd.Series((series1 > series2) & (series1.shift(1) <= series2.shift(1))) 234 | 235 | if direction is None or direction == "below": 236 | below = pd.Series((series1 < series2) & (series1.shift(1) >= series2.shift(1))) 237 | 238 | if direction is None: 239 | return above | below 240 | 241 | return above if direction == "above" else below 242 | 243 | 244 | def crossed_above(series1, series2): 245 | return crossed(series1, series2, "above") 246 | 247 | 248 | def crossed_below(series1, series2): 249 | return crossed(series1, series2, "below") 250 | 251 | 252 | # --------------------------------------------- 253 | 254 | 255 | def rolling_std(series, window=200, min_periods=None): 256 | min_periods = window if min_periods is None else min_periods 257 | if min_periods == window and len(series) > window: 258 | return numpy_rolling_std(series, window, True) 259 | else: 260 | try: 261 | return series.rolling(window=window, min_periods=min_periods).std() 262 | except Exception as e: # noqa: F841 263 | return pd.Series(series).rolling(window=window, min_periods=min_periods).std() 264 | 265 | 266 | # --------------------------------------------- 267 | 268 | 269 | def rolling_mean(series, window=200, min_periods=None): 270 | min_periods = window if min_periods is None else min_periods 271 | if min_periods == window and len(series) > window: 272 | return numpy_rolling_mean(series, window, True) 273 | else: 274 | try: 275 | return series.rolling(window=window, min_periods=min_periods).mean() 276 | except Exception as e: # noqa: F841 277 | return pd.Series(series).rolling(window=window, min_periods=min_periods).mean() 278 | 279 | 280 | # --------------------------------------------- 281 | 282 | 283 | def rolling_min(series, window=14, min_periods=None): 284 | min_periods = window if min_periods is None else min_periods 285 | try: 286 | return series.rolling(window=window, min_periods=min_periods).min() 287 | except Exception as e: # noqa: F841 288 | return pd.Series(series).rolling(window=window, min_periods=min_periods).min() 289 | 290 | 291 | # --------------------------------------------- 292 | 293 | 294 | def rolling_max(series, window=14, min_periods=None): 295 | min_periods = window if min_periods is None else min_periods 296 | try: 297 | return series.rolling(window=window, min_periods=min_periods).max() 298 | except Exception as e: # noqa: F841 299 | return pd.Series(series).rolling(window=window, min_periods=min_periods).max() 300 | 301 | 302 | # --------------------------------------------- 303 | 304 | 305 | def rolling_weighted_mean(series, window=200, min_periods=None): 306 | min_periods = window if min_periods is None else min_periods 307 | try: 308 | return series.ewm(span=window, min_periods=min_periods).mean() 309 | except Exception as e: # noqa: F841 310 | return pd.ewma(series, span=window, min_periods=min_periods) 311 | 312 | 313 | # --------------------------------------------- 314 | 315 | 316 | def hull_moving_average(series, window=200, min_periods=None): 317 | min_periods = window if min_periods is None else min_periods 318 | ma = (2 * rolling_weighted_mean(series, window / 2, min_periods)) - rolling_weighted_mean( 319 | series, window, min_periods 320 | ) 321 | return rolling_weighted_mean(ma, np.sqrt(window), min_periods) 322 | 323 | 324 | # --------------------------------------------- 325 | 326 | 327 | def sma(series, window=200, min_periods=None): 328 | return rolling_mean(series, window=window, min_periods=min_periods) 329 | 330 | 331 | # --------------------------------------------- 332 | 333 | 334 | def wma(series, window=200, min_periods=None): 335 | return rolling_weighted_mean(series, window=window, min_periods=min_periods) 336 | 337 | 338 | # --------------------------------------------- 339 | 340 | 341 | def hma(series, window=200, min_periods=None): 342 | return hull_moving_average(series, window=window, min_periods=min_periods) 343 | 344 | 345 | # --------------------------------------------- 346 | 347 | 348 | def vwap(bars): 349 | """ 350 | calculate vwap of entire time series 351 | (input can be pandas series or numpy array) 352 | bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] 353 | """ 354 | raise ValueError( 355 | "using `qtpylib.vwap` facilitates lookahead bias. Please use " 356 | "`qtpylib.rolling_vwap` instead, which calculates vwap in a rolling manner." 357 | ) 358 | # typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values 359 | # volume = bars['volume'].values 360 | 361 | # return pd.Series(index=bars.index, 362 | # data=np.cumsum(volume * typical) / np.cumsum(volume)) 363 | 364 | 365 | # --------------------------------------------- 366 | 367 | 368 | def rolling_vwap(bars, window=200, min_periods=None): 369 | """ 370 | calculate vwap using moving window 371 | (input can be pandas series or numpy array) 372 | bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] 373 | """ 374 | min_periods = window if min_periods is None else min_periods 375 | 376 | typical = (bars["high"] + bars["low"] + bars["close"]) / 3 377 | volume = bars["volume"] 378 | 379 | left = (volume * typical).rolling(window=window, min_periods=min_periods).sum() 380 | right = volume.rolling(window=window, min_periods=min_periods).sum() 381 | 382 | return ( 383 | pd.Series(index=bars.index, data=(left / right)) 384 | .replace([np.inf, -np.inf], float("NaN")) 385 | .ffill() 386 | ) 387 | 388 | 389 | # --------------------------------------------- 390 | 391 | 392 | def rsi(series, window=14): 393 | """ 394 | compute the n period relative strength indicator 395 | """ 396 | 397 | # 100-(100/relative_strength) 398 | deltas = np.diff(series) 399 | seed = deltas[: window + 1] 400 | 401 | # default values 402 | ups = seed[seed > 0].sum() / window 403 | downs = -seed[seed < 0].sum() / window 404 | rsival = np.zeros_like(series) 405 | rsival[:window] = 100.0 - 100.0 / (1.0 + ups / downs) 406 | 407 | # period values 408 | for i in range(window, len(series)): 409 | delta = deltas[i - 1] 410 | if delta > 0: 411 | upval = delta 412 | downval = 0 413 | else: 414 | upval = 0 415 | downval = -delta 416 | 417 | ups = (ups * (window - 1) + upval) / window 418 | downs = (downs * (window - 1.0) + downval) / window 419 | rsival[i] = 100.0 - 100.0 / (1.0 + ups / downs) 420 | 421 | # return rsival 422 | return pd.Series(index=series.index, data=rsival) 423 | 424 | 425 | # --------------------------------------------- 426 | 427 | 428 | def macd(series, fast=3, slow=10, smooth=16): 429 | """ 430 | compute the MACD (Moving Average Convergence/Divergence) 431 | using a fast and slow exponential moving avg' 432 | return value is emaslow, emafast, macd which are len(x) arrays 433 | """ 434 | macd_line = rolling_weighted_mean(series, window=fast) - rolling_weighted_mean( 435 | series, window=slow 436 | ) 437 | signal = rolling_weighted_mean(macd_line, window=smooth) 438 | histogram = macd_line - signal 439 | # return macd_line, signal, histogram 440 | return pd.DataFrame( 441 | index=series.index, 442 | data={"macd": macd_line.values, "signal": signal.values, "histogram": histogram.values}, 443 | ) 444 | 445 | 446 | # --------------------------------------------- 447 | 448 | 449 | def bollinger_bands(series, window=20, stds=2): 450 | ma = rolling_mean(series, window=window, min_periods=1) 451 | std = rolling_std(series, window=window, min_periods=1) 452 | upper = ma + std * stds 453 | lower = ma - std * stds 454 | 455 | return pd.DataFrame(index=series.index, data={"upper": upper, "mid": ma, "lower": lower}) 456 | 457 | 458 | # --------------------------------------------- 459 | 460 | 461 | def weighted_bollinger_bands(series, window=20, stds=2): 462 | ema = rolling_weighted_mean(series, window=window) 463 | std = rolling_std(series, window=window) 464 | upper = ema + std * stds 465 | lower = ema - std * stds 466 | 467 | return pd.DataFrame( 468 | index=series.index, data={"upper": upper.values, "mid": ema.values, "lower": lower.values} 469 | ) 470 | 471 | 472 | # --------------------------------------------- 473 | 474 | 475 | def returns(series): 476 | try: 477 | res = (series / series.shift(1) - 1).replace([np.inf, -np.inf], float("NaN")) 478 | except Exception as e: # noqa: F841 479 | res = nans(len(series)) 480 | 481 | return pd.Series(index=series.index, data=res) 482 | 483 | 484 | # --------------------------------------------- 485 | 486 | 487 | def log_returns(series): 488 | try: 489 | res = np.log(series / series.shift(1)).replace([np.inf, -np.inf], float("NaN")) 490 | except Exception as e: # noqa: F841 491 | res = nans(len(series)) 492 | 493 | return pd.Series(index=series.index, data=res) 494 | 495 | 496 | # --------------------------------------------- 497 | 498 | 499 | def implied_volatility(series, window=252): 500 | try: 501 | logret = np.log(series / series.shift(1)).replace([np.inf, -np.inf], float("NaN")) 502 | res = numpy_rolling_std(logret, window) * np.sqrt(window) 503 | except Exception as e: # noqa: F841 504 | res = nans(len(series)) 505 | 506 | return pd.Series(index=series.index, data=res) 507 | 508 | 509 | # --------------------------------------------- 510 | 511 | 512 | def keltner_channel(bars, window=14, atrs=2): 513 | typical_mean = rolling_mean(typical_price(bars), window) 514 | atrval = atr(bars, window) * atrs 515 | 516 | upper = typical_mean + atrval 517 | lower = typical_mean - atrval 518 | 519 | return pd.DataFrame( 520 | index=bars.index, 521 | data={"upper": upper.values, "mid": typical_mean.values, "lower": lower.values}, 522 | ) 523 | 524 | 525 | # --------------------------------------------- 526 | 527 | 528 | def roc(series, window=14): 529 | """ 530 | compute rate of change 531 | """ 532 | res = (series - series.shift(window)) / series.shift(window) 533 | return pd.Series(index=series.index, data=res) 534 | 535 | 536 | # --------------------------------------------- 537 | 538 | 539 | def cci(series, window=14): 540 | """ 541 | compute commodity channel index 542 | """ 543 | price = typical_price(series) 544 | typical_mean = rolling_mean(price, window) 545 | res = (price - typical_mean) / (0.015 * np.std(typical_mean)) 546 | return pd.Series(index=series.index, data=res) 547 | 548 | 549 | # --------------------------------------------- 550 | 551 | 552 | def stoch(df, window=14, d=3, k=3, fast=False): 553 | """ 554 | compute the n period relative strength indicator 555 | http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html 556 | """ 557 | 558 | my_df = pd.DataFrame(index=df.index) 559 | 560 | my_df["rolling_max"] = df["high"].rolling(window).max() 561 | my_df["rolling_min"] = df["low"].rolling(window).min() 562 | 563 | my_df["fast_k"] = ( 564 | 100 * (df["close"] - my_df["rolling_min"]) / (my_df["rolling_max"] - my_df["rolling_min"]) 565 | ) 566 | my_df["fast_d"] = my_df["fast_k"].rolling(d).mean() 567 | 568 | if fast: 569 | return my_df.loc[:, ["fast_k", "fast_d"]] 570 | 571 | my_df["slow_k"] = my_df["fast_k"].rolling(k).mean() 572 | my_df["slow_d"] = my_df["slow_k"].rolling(d).mean() 573 | 574 | return my_df.loc[:, ["slow_k", "slow_d"]] 575 | 576 | 577 | # --------------------------------------------- 578 | 579 | 580 | def zlma(series, window=20, min_periods=None, kind="ema"): 581 | """ 582 | John Ehlers' Zero lag (exponential) moving average 583 | https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average 584 | """ 585 | min_periods = window if min_periods is None else min_periods 586 | 587 | lag = (window - 1) // 2 588 | series = 2 * series - series.shift(lag) 589 | if kind in ["ewm", "ema"]: 590 | return wma(series, lag, min_periods) 591 | elif kind == "hma": 592 | return hma(series, lag, min_periods) 593 | return sma(series, lag, min_periods) 594 | 595 | 596 | def zlema(series, window, min_periods=None): 597 | return zlma(series, window, min_periods, kind="ema") 598 | 599 | 600 | def zlsma(series, window, min_periods=None): 601 | return zlma(series, window, min_periods, kind="sma") 602 | 603 | 604 | def zlhma(series, window, min_periods=None): 605 | return zlma(series, window, min_periods, kind="hma") 606 | 607 | 608 | # --------------------------------------------- 609 | 610 | 611 | def zscore(bars, window=20, stds=1, col="close"): 612 | """get zscore of price""" 613 | std = numpy_rolling_std(bars[col], window) 614 | mean = numpy_rolling_mean(bars[col], window) 615 | return (bars[col] - mean) / (std * stds) 616 | 617 | 618 | # --------------------------------------------- 619 | 620 | 621 | def pvt(bars): 622 | """Price Volume Trend""" 623 | trend = ((bars["close"] - bars["close"].shift(1)) / bars["close"].shift(1)) * bars["volume"] 624 | return trend.cumsum() 625 | 626 | 627 | def chopiness(bars, window=14): 628 | atrsum = true_range(bars).rolling(window).sum() 629 | highs = bars["high"].rolling(window).max() 630 | lows = bars["low"].rolling(window).min() 631 | return 100 * np.log10(atrsum / (highs - lows)) / np.log10(window) 632 | 633 | 634 | # ============================================= 635 | 636 | 637 | PandasObject.session = session 638 | PandasObject.atr = atr 639 | PandasObject.bollinger_bands = bollinger_bands 640 | PandasObject.cci = cci 641 | PandasObject.crossed = crossed 642 | PandasObject.crossed_above = crossed_above 643 | PandasObject.crossed_below = crossed_below 644 | PandasObject.heikinashi = heikinashi 645 | PandasObject.hull_moving_average = hull_moving_average 646 | PandasObject.ibs = ibs 647 | PandasObject.implied_volatility = implied_volatility 648 | PandasObject.keltner_channel = keltner_channel 649 | PandasObject.log_returns = log_returns 650 | PandasObject.macd = macd 651 | PandasObject.returns = returns 652 | PandasObject.roc = roc 653 | PandasObject.rolling_max = rolling_max 654 | PandasObject.rolling_min = rolling_min 655 | PandasObject.rolling_mean = rolling_mean 656 | PandasObject.rolling_std = rolling_std 657 | PandasObject.rsi = rsi 658 | PandasObject.stoch = stoch 659 | PandasObject.zscore = zscore 660 | PandasObject.pvt = pvt 661 | PandasObject.chopiness = chopiness 662 | PandasObject.tdi = tdi 663 | PandasObject.true_range = true_range 664 | PandasObject.mid_price = mid_price 665 | PandasObject.typical_price = typical_price 666 | PandasObject.vwap = vwap 667 | PandasObject.rolling_vwap = rolling_vwap 668 | PandasObject.weighted_bollinger_bands = weighted_bollinger_bands 669 | PandasObject.rolling_weighted_mean = rolling_weighted_mean 670 | 671 | PandasObject.sma = sma 672 | PandasObject.wma = wma 673 | PandasObject.ema = wma 674 | PandasObject.hma = hma 675 | 676 | PandasObject.zlsma = zlsma 677 | PandasObject.zlwma = zlema 678 | PandasObject.zlema = zlema 679 | PandasObject.zlhma = zlhma 680 | PandasObject.zlma = zlma 681 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | # pragma pylint: disable=missing-docstring 2 | import json 3 | import logging 4 | 5 | import pytest 6 | from pandas import DataFrame 7 | 8 | from technical.util import ticker_history_to_dataframe 9 | 10 | logging.getLogger("").setLevel(logging.INFO) 11 | 12 | 13 | @pytest.fixture(scope="class") 14 | def testdata_1m_btc() -> DataFrame: 15 | with open("tests/testdata/UNITTEST_BTC-1m.json") as data_file: 16 | return ticker_history_to_dataframe(json.load(data_file)) 17 | -------------------------------------------------------------------------------- /tests/exchange/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/tests/exchange/__init__.py -------------------------------------------------------------------------------- /tests/image/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/tests/image/__init__.py -------------------------------------------------------------------------------- /tests/image/test_get_coin_in_image.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freqtrade/technical/57958bb059d4a798132f42605064b33163d46ae7/tests/image/test_get_coin_in_image.py -------------------------------------------------------------------------------- /tests/test_indicator_helpers.py: -------------------------------------------------------------------------------- 1 | # pragma pylint: disable=missing-docstring 2 | 3 | import pandas as pd 4 | 5 | from technical.indicator_helpers import went_down, went_up 6 | 7 | 8 | def test_went_up(): 9 | series = pd.Series([1, 2, 3, 1]) 10 | assert went_up(series).equals(pd.Series([False, True, True, False])) 11 | 12 | 13 | def test_went_down(): 14 | series = pd.Series([1, 2, 3, 1]) 15 | assert went_down(series).equals(pd.Series([False, False, False, True])) 16 | -------------------------------------------------------------------------------- /tests/test_indicators.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | 4 | def test_atr(testdata_1m_btc): 5 | from technical.indicators import atr 6 | 7 | result = testdata_1m_btc 8 | result["atr"] = atr(testdata_1m_btc, 14) 9 | 10 | result = result.tail(10) 11 | 12 | assert result["atr"].all() > 0 13 | 14 | 15 | def test_atr_percent(testdata_1m_btc): 16 | from technical.indicators import atr_percent 17 | 18 | result = testdata_1m_btc 19 | result["atr"] = atr_percent(testdata_1m_btc, 14) 20 | 21 | result = result.tail(10) 22 | 23 | assert result["atr"].all() > 0 24 | 25 | 26 | def test_bollinger_bands(testdata_1m_btc): 27 | from technical.indicators import bollinger_bands 28 | 29 | result = bollinger_bands(testdata_1m_btc) 30 | 31 | result = result.tail(10) 32 | 33 | assert result["bb_lower"].all() > 0 34 | assert result["bb_middle"].all() > 0 35 | assert result["bb_upper"].all() > 0 36 | 37 | 38 | def test_chaikin_money_flow(testdata_1m_btc): 39 | from technical.indicators import chaikin_money_flow, cmf 40 | 41 | assert cmf is chaikin_money_flow 42 | 43 | result = chaikin_money_flow(testdata_1m_btc, 14) 44 | 45 | # drop nan, they are expected, based on the period 46 | result = result[~numpy.isnan(result)] 47 | 48 | assert result.min() >= -1 49 | assert result.max() <= 1 50 | 51 | 52 | def test_fibonacci_retracements(testdata_1m_btc): 53 | from technical.indicators import fibonacci_retracements 54 | 55 | result = fibonacci_retracements(testdata_1m_btc) 56 | 57 | assert result.min() < 1.0e-8 58 | assert result.max() > 1.0 - 1.0e-8 59 | 60 | 61 | def test_return_on_investment(): 62 | from pandas import DataFrame 63 | 64 | from technical.indicators import return_on_investment 65 | 66 | close = numpy.array([100, 200, 300, 400, 500, 600]) 67 | buys = numpy.array([[0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0]]) 68 | rois = numpy.array( 69 | [ 70 | [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 71 | [0.0, 0.0, 50.0, 0.0, 25.0, 0.0], 72 | [0.0, 100.0, 0.0, 33.33, 0.0, 20.0], 73 | ] 74 | ) 75 | 76 | for buy, roi in zip(buys, rois): 77 | dataframe = DataFrame() 78 | dataframe["close"] = close 79 | dataframe["buy"] = buy 80 | 81 | dataframe = return_on_investment(dataframe, decimals=2) 82 | assert (dataframe["roi"] >= 0).all() 83 | assert (dataframe.loc[dataframe["buy"] == 1, "roi"] == 0).all() 84 | assert numpy.allclose(numpy.array(dataframe["roi"]), roi) 85 | -------------------------------------------------------------------------------- /tests/test_indicators_generic.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pandas import DataFrame, Series 3 | 4 | import technical.indicators as ti 5 | 6 | 7 | @pytest.mark.parametrize( 8 | "function,args,responsetype,new_column_names", 9 | [ 10 | (ti.atr_percent, [], "series", None), 11 | (ti.atr, [], "series", None), 12 | (ti.bollinger_bands, [], "df", ["bb_lower", "bb_middle", "bb_upper"]), 13 | (ti.chaikin_money_flow, [], "series", None), 14 | (ti.MADR, [], "df", ["rate", "plusdev", "minusdev", "stdcenter"]), 15 | (ti.PMAX, [], "df", ["ATR_10", "pm_10_3_12_1", "pmX_10_3_12_1"]), 16 | (ti.RMI, [], "series", None), 17 | (ti.SSLChannels, [], "tuple", None), 18 | (ti.TKE, [], "tuple", None), 19 | (ti.VIDYA, [], "series", None), 20 | (ti.atr_percent, [], "series", None), 21 | (ti.chaikin_money_flow, [], "series", None), 22 | (ti.chopiness, [], "series", None), 23 | (ti.cmf, [], "series", None), 24 | (ti.ema, [10], "series", None), 25 | (ti.fibonacci_retracements, [], "series", None), 26 | (ti.hull_moving_average, [10], "series", None), 27 | (ti.ichimoku, [], "dict", None), 28 | (ti.laguerre, [], "series", None), 29 | (ti.madrid_sqz, [], "tuple", None), 30 | (ti.mmar, [], "tuple", None), 31 | (ti.osc, [], "series", None), 32 | # (ti.return_on_investment, [], 'series', None), 33 | (ti.sma, [10], "series", None), 34 | # (ti.stc, [], "series", None), # disabled for slightly different results on ARM 35 | (ti.td_sequential, [], "df", ["TD_count"]), 36 | (ti.dema, [10], "series", None), 37 | (ti.tema, [10], "series", None), 38 | (ti.tv_hma, [10], "series", None), 39 | (ti.tv_wma, [10], "series", None), 40 | (ti.tv_alma, [], "series", None), 41 | (ti.vfi, [], "tuple", None), 42 | (ti.vpci, [], "series", None), 43 | (ti.vpcii, [], "series", None), 44 | (ti.vwma, [10], "series", None), 45 | (ti.vwmacd, [], "df", ["vwmacd", "signal", "hist"]), 46 | (ti.williams_percent, [], "series", None), 47 | ], 48 | ) 49 | def test_indicators_generic_interface( 50 | function, args, responsetype, new_column_names, testdata_1m_btc, snapshot 51 | ): 52 | assert 13680 == len(testdata_1m_btc) 53 | # Ensure all builtin indicators have the same interface 54 | input_df = testdata_1m_btc.iloc[-1000:].copy() 55 | res = function(input_df, *args) 56 | 57 | final_result = None 58 | if responsetype == "tuple": 59 | assert isinstance(res, tuple) 60 | assert len(res[0]) == 1000 61 | assert len(res[1]) == 1000 62 | final_result = input_df 63 | for i, x in enumerate(res): 64 | final_result.loc[:, f"{function.__name__}_{i}"] = x 65 | 66 | elif responsetype == "dict": 67 | assert isinstance(res, dict) 68 | assert len(res["tenkan_sen"]) == 1000 69 | final_result = input_df 70 | 71 | for k, v in res.items(): 72 | final_result.loc[:, f"{function.__name__}_{k}"] = v 73 | elif responsetype == "series": 74 | assert isinstance(res, Series) 75 | assert len(res) == 1000 76 | final_result = input_df 77 | final_result.loc[:, function.__name__] = res 78 | elif responsetype == "df": 79 | # Result is dataframe 80 | assert isinstance(res, DataFrame) 81 | assert len(res) == 1000 82 | final_result = res 83 | if len(new_column_names) > 0: 84 | assert len(res.columns) == len(new_column_names) + 6 85 | default_columns = ["date", "open", "high", "low", "close", "volume"] 86 | cols = set(res.columns) 87 | assert cols == set(new_column_names + default_columns) 88 | # assert set() 89 | assert all([x in res.columns for x in new_column_names]) 90 | else: 91 | assert False 92 | 93 | # Ensure full output is serialized 94 | # can probably be removed once https://github.com/syrupy-project/syrupy/issues/887 95 | # is implemented 96 | assert isinstance(final_result, DataFrame) 97 | assert len(final_result) == 1000 98 | csv_string = final_result.to_csv(index=False, float_format="%.10f") 99 | assert snapshot == csv_string 100 | -------------------------------------------------------------------------------- /tests/test_util.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import pandas as pd 4 | 5 | from technical.indicators import chaikin_money_flow 6 | from technical.util import resample_to_interval, resampled_merge, ticker_history_to_dataframe 7 | 8 | 9 | def test_ticker_to_dataframe(): 10 | with open("tests/testdata/UNITTEST_BTC-1m.json") as data_file: 11 | data = ticker_history_to_dataframe(json.load(data_file)) 12 | assert len(data) > 0 13 | 14 | 15 | def test_resample_to_interval(testdata_1m_btc): 16 | result = resample_to_interval(testdata_1m_btc, 5) 17 | 18 | # should be roughly a factor 5 19 | assert len(testdata_1m_btc) / len(result) > 4.5 20 | assert len(testdata_1m_btc) / len(result) < 5.5 21 | 22 | 23 | def test_resampled_merge(testdata_1m_btc): 24 | resampled = resample_to_interval(testdata_1m_btc, 5) 25 | 26 | merged = resampled_merge(testdata_1m_btc, resampled) 27 | 28 | assert len(merged) == len(testdata_1m_btc) 29 | assert "resample_5_open" in merged 30 | assert "resample_5_close" in merged 31 | assert "resample_5_low" in merged 32 | assert "resample_5_high" in merged 33 | 34 | assert "resample_5_date" in merged 35 | assert "resample_5_volume" in merged 36 | # Verify the assignment goes to the correct candle 37 | # If resampling to 5m, then the resampled value needs to be on the 5m candle. 38 | date = pd.to_datetime("2017-11-14 22:45:00", utc=True) 39 | assert merged.loc[merged["date"] == "2017-11-14 22:48:00", "resample_5_date"].iloc[0] != date 40 | # The 5m candle for 22:45 is available at 22:50, 41 | # when both :49 1m and :45 5m candles close 42 | assert merged.loc[merged["date"] == "2017-11-14 22:49:00", "resample_5_date"].iloc[0] == date 43 | assert merged.loc[merged["date"] == "2017-11-14 22:50:00", "resample_5_date"].iloc[0] == date 44 | assert merged.loc[merged["date"] == "2017-11-14 22:51:00", "resample_5_date"].iloc[0] == date 45 | assert merged.loc[merged["date"] == "2017-11-14 22:52:00", "resample_5_date"].iloc[0] == date 46 | assert merged.loc[merged["date"] == "2017-11-14 22:53:00", "resample_5_date"].iloc[0] == date 47 | # The 5m candle for 22:50 is available at 22:54, 48 | # when both :54 1m and :50 5m candles close 49 | date = pd.to_datetime("2017-11-14 22:50:00", utc=True) 50 | assert merged.loc[merged["date"] == "2017-11-14 22:54:00", "resample_5_date"].iloc[0] == date 51 | assert merged.loc[merged["date"] == "2017-11-14 22:55:00", "resample_5_date"].iloc[0] == date 52 | assert merged.loc[merged["date"] == "2017-11-14 22:56:00", "resample_5_date"].iloc[0] == date 53 | assert merged.loc[merged["date"] == "2017-11-14 22:57:00", "resample_5_date"].iloc[0] == date 54 | assert merged.loc[merged["date"] == "2017-11-14 22:58:00", "resample_5_date"].iloc[0] == date 55 | 56 | 57 | def test_resampled_merge_contains_indicator(testdata_1m_btc): 58 | resampled = resample_to_interval(testdata_1m_btc, 5) 59 | resampled["cmf"] = chaikin_money_flow(resampled, 5) 60 | merged = resampled_merge(testdata_1m_btc, resampled) 61 | 62 | print(merged) 63 | assert "resample_5_cmf" in merged 64 | --------------------------------------------------------------------------------