From ce1316c2022692a9dcb5bb15cbf42add3eec8581 Mon Sep 17 00:00:00 2001 From: conache Date: Wed, 6 Mar 2024 17:53:48 +0200 Subject: [PATCH] Basic inference node setup --- .gitignore | 11 +++ CONTRIBUTING.md | 18 ++++ Dockerfile | 17 ++++ Dockerfile_b7s | 8 ++ LICENSE | 201 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 128 +++++++++++++++++++++++++++++ app.py | 62 ++++++++++++++ config.py | 5 ++ docker-compose.yml | 93 +++++++++++++++++++++ gunicorn_conf.py | 12 +++ main.py | 25 ++++++ model.py | 101 +++++++++++++++++++++++ requirements.txt | 6 ++ update_app.py | 20 +++++ updater.py | 54 ++++++++++++ 15 files changed, 761 insertions(+) create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 Dockerfile_b7s create mode 100644 LICENSE create mode 100644 README.md create mode 100644 app.py create mode 100644 config.py create mode 100644 docker-compose.yml create mode 100644 gunicorn_conf.py create mode 100644 main.py create mode 100644 model.py create mode 100644 requirements.txt create mode 100644 update_app.py create mode 100644 updater.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e865921 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +.DS_Store +__pycache__ +*.pyc +.lake_cache/* +logs/* +.env +keys +data +worker-data +head-data +lib \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..cfba094 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,18 @@ +Any contribution that you make to this repository will +be under the Apache 2 License, as dictated by that +[license](http://www.apache.org/licenses/LICENSE-2.0.html): + +~~~ +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. +~~~ + +Contributors must sign-off each commit by adding a `Signed-off-by: ...` +line to commit messages to certify that they have the right to submit +the code they are contributing to the project according to the +[Developer Certificate of Origin (DCO)](https://developercertificate.org/). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..df82d46 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +# Use an official Python runtime as the base image +FROM amd64/python:3.9-buster as project_env + +# Set the working directory in the container +WORKDIR /app + +# Install dependencies +COPY requirements.txt requirements.txt +RUN pip install --upgrade pip setuptools \ + && pip install -r requirements.txt + +FROM project_env + +COPY . /app/ + +# Set the entrypoint command +CMD ["gunicorn", "--conf", "/app/gunicorn_conf.py", "main:app"] diff --git a/Dockerfile_b7s b/Dockerfile_b7s new file mode 100644 index 0000000..acf35d8 --- /dev/null +++ b/Dockerfile_b7s @@ -0,0 +1,8 @@ +FROM --platform=linux/amd64 696230526504.dkr.ecr.us-east-1.amazonaws.com/allora-inference-base:latest +# FROM --platform=linux/amd64 allora-inference-base:dev + +USER root +RUN pip install requests + +USER appuser +COPY main.py /app/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9e864f2 --- /dev/null +++ b/README.md @@ -0,0 +1,128 @@ +# Basic ETH price prediction node + +Example Allora network worker node: a node to provide price predictions of ETH. + +One of the primary objectives is to demonstrate the utilization of a basic inference model operating within a dedicated container. The purpose is to showcase its seamless integration with the Allora network infrastructure, enabling it to contribute with valuable inferences. + +# Components + +* **head**: An Allora network head node. This is not required for running your node in the Allora network, but it will help for testing your node emulating a network. +* **worker**: The node that will respond to inference requests from the Allora network heads. +* **inference**: A container that conducts inferences, maintains the model state, and responds to internal inference requests via a Flask application. The node operates with a basic linear regression model for price predictions. +* **updater**: An example of a cron-like container, that will update the data of the inference node. +Check the `docker-compose.yml` file (or see docker-compose section below) to see separate components: + +# Inference request flow + +When a request is made to the head, it relays this request to a number of workers associated with this head. The request specifies a function to run which will execute a wasm code that will call the `main.py` file in the worker. The worker will check the argument (the coin to predict for), and make a request to the `inference` node, and return this value to the `head`, which prepares the response from all of its nodes and sends it back to the requestor. + +# Docker setup + +## Structure + +- head and worker nodes are built upon `Dockerfile_b7s` file +- inference and updater nodes are built with `Dockerfile`. This works as an example on how to reuse your current model containers, just by setting up a Flask web application in front with minimal integration work with the Allora network nodes. + +The `Dockerfile_b7s` file is functional but simple, so you may want to change it to fit your needs, if you attempt to expand upon the current setup. +For further details, please check the base repo [allora-inference-base](https://github.com/allora-network/allora-inference-base). + +### Application path + +By default, the application runtime lives under `/app`, as well as the Python code the worker provides (`/app/main.py`). The current user needs to have write permissions on `/app/runtime`. + +### Data volume and permissions + +It is recommended to mount `/data` as a volume, to persist the node databases of peers, functions, etc. which are defined in the flags passed to the worker. +You can create this folder e.g. `mkdir data` in the repo root directory. + +It is recommended to set up two different `/data` volumes. It is suggested to use `data-worker` for the worker, `data-head` for the head. + +Troubleshooting: A conflict may happen between the uid/gid of the user inside the container(1001) with the permissions of your own user. +To make the container user have permissions to write on the `/data` volume, you may need to set the UID/GID from the user running the container. You can get those in linux/osx via `id -u` and `id -g`. +The current `docker-compose.yml` file shows the `worker` service setting UID and GID. As well, the `Dockerfile` also sets UID/GID values. + + +# docker-compose +A full working example is provided in `docker-compose`. + +## Structure +There is a docker-compose.yml provided that sets up one head node, one worker node, one inference node, and an updater node. +Please find details about options on the [allora-inference-base](https://github.com/allora-network/allora-inference-base) repo. + +## Dependencies +Ensure the following dependencies are in place before proceeding: + +- **Docker Image**: Have an available image of the `allora-inference-base`, and reference it as a base on the `FROM` of the `Dockerfile_b7s` file. +- **Keys Setup**: Create a set of keys for your head and worker and use them in the head and worker configuration. If no keys are specified in the volumes, new keys are created. However, the worker will need to specify the `peer_id` of the head for defining it as a `BOOT_NODES`. + +## Connecting to the Allora network + In order to connect the an Allora network to provide inferences, both the head and the worker need to register against it. More details on [allora-inference-base](https://github.com/allora-network/allora-inference-base) repo. +The following optional flags are used in the `command:` section of the `docker-compose.yml` file to define the connectivity with the Allora network. + +``` +--allora-chain-key-name=index-provider # your local key name in your keyring +--allora-chain-restore-mnemonic='pet sock excess ...' # your node's Allora address mnemonic +--allora-node-rpc-address= # RPC address of a node in the chain +--allora-chain-topic-id= # The topic id from the chain that you want to provide predictions for +``` +In order for the nodes to register with the chain, a funded address is needed first. +If these flags are not provided, the nodes will not register to the appchain and will not attempt to connect to the appchain. + +# Setup +Once this is set up, run `docker compose up head worker inference` +This will bring up the head, the worker and the inference nodes (which will run an initial update). The `updater` node is a companion for updating the inference node state and it's meant to hit the /update endpoint on the inference service. It is expected to run periodically, being crucial for maintaining the accuracy of the inferences. + +## Testing docker-compose setup + +The head node has the only open port, and responds to requests in port 6000. + +Example request: +``` +curl --location 'http://localhost:6000/api/v1/functions/execute' \ +--header 'Content-Type: application/json' \ +--data '{ + "function_id": "bafybeigpiwl3o73zvvl6dxdqu7zqcub5mhg65jiky2xqb4rdhfmikswzqm", + "method": "allora-inference-function.wasm", + "parameters": null, + "topic": "1", + "config": { + "env_vars": [ + { + "name": "BLS_REQUEST_PATH", + "value": "/api" + }, + { + "name": "ALLORA_ARG_PARAMS", + "value": "ETH" + } + ], + "number_of_nodes": -1, + "timeout": 2 + } +}' +``` +Response: +``` +{"code":"200","request_id":"e3daeda0-c849-4b68-b21d-8f51e42bb9d3","results":[{"result":{"stdout":"{\"value\":\"2564.250058819078\"}\n\n\n","stderr":"","exit_code":0},"peers":["12D3KooWG8dHctRt6ctakJfG5masTnLaKM6xkudoR5BxLDRSrgVt"],"frequency":100}],"cluster":{"peers":["12D3KooWG8dHctRt6ctakJfG5masTnLaKM6xkudoR5BxLDRSrgVt"]}} +``` + +# Testing inference only +This setup allows to develop your model without need for bringing up the head and worker. +To only test the inference model, you can just: +- In docker-compose.yml, under `inference` service, uncomment the lines: + ``` + ports: + - "8000:8000" + ``` +- Run `docker compose up --build inference` and wait for the initial data load. +- Requests can now be sent, e.g. request ETH price inferences as in: + ``` + $ curl http://localhost:8000/inference/ETH + {"value":"2564.2513659239594"} + ``` + or update the node's internal state (download pricing data, train and update the model): + ``` + $ curl http://localhost:8000/update + 0 + ``` + diff --git a/app.py b/app.py new file mode 100644 index 0000000..32424c5 --- /dev/null +++ b/app.py @@ -0,0 +1,62 @@ +import json +import pickle +import pandas as pd +import numpy as np +from datetime import datetime +from flask import Flask, jsonify, Response +from model import download_data, format_data, train_model +from config import model_file_path + +app = Flask(__name__) + + +def update_data(): + """Download price data, format data and train model.""" + download_data() + format_data() + train_model() + + +def get_eth_inference(): + """Load model and predict current price.""" + with open(model_file_path, "rb") as f: + loaded_model = pickle.load(f) + + now_timestamp = pd.Timestamp(datetime.now()).timestamp() + X_new = np.array([now_timestamp]).reshape(-1, 1) + current_price_pred = loaded_model.predict(X_new) + + return current_price_pred[0][0] + + +@app.route("/inference/") +def generate_inference(token): + """Generate inference for given token.""" + if not token or token != "ETH": + error_msg = "Token is required" if not token else "Token not supported" + return Response( + json.dumps({"error": error_msg}), status=400, mimetype="application/json" + ) + + try: + inference = get_eth_inference() + return jsonify({"value": str(inference)}) + except Exception as e: + return Response( + json.dumps({"error": str(e)}), status=500, mimetype="application/json" + ) + + +@app.route("/update") +def update(): + """Update data and return status.""" + try: + update_data() + return "0" + except Exception: + return "1" + + +if __name__ == "__main__": + update_data() + app.run(host="0.0.0.0", port=8000) diff --git a/config.py b/config.py new file mode 100644 index 0000000..c1b91db --- /dev/null +++ b/config.py @@ -0,0 +1,5 @@ +import os + +app_base_path = os.getenv("APP_BASE_PATH", default=os.getcwd()) +data_base_path = os.path.join(app_base_path, "data") +model_file_path = os.path.join(data_base_path, "model.pkl") diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..02bf686 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,93 @@ +version: '3' + +services: + inference: + container_name: inference-basic-eth-pred + build: + context: . + command: python -u /app/app.py + ports: + - "8000:8000" + networks: + eth-model-local: + aliases: + - inference + ipv4_address: 172.22.0.4 + + worker: + container_name: worker-basic-eth-pred + environment: + - INFERENCE_API_ADDRESS=http://inference:8000 + - HOME=/data + build: + context: . + dockerfile: Dockerfile_b7s + entrypoint: + - "/bin/bash" + - "-c" + - | + if [ ! -f /data/keys/priv.bin ]; then + echo "Generating new private keys..." + mkdir -p /data/keys + cd /data/keys + allora-keys + fi + # Change boot-nodes below to the key advertised by your head + allora-node --role=worker --peer-db=/data/peerdb --function-db=/data/function-db \ + --runtime-path=/app/runtime --runtime-cli=bls-runtime --workspace=/data/workspace \ + --private-key=/data/keys/priv.bin --log-level=debug --port=9011 \ + --boot-nodes=/ip4/172.22.0.100/tcp/9010/p2p/12D3KooWSBJucc8S3YdLH8n5UqTQpSbNjwEjcnYCW8zWuPhDAFHY \ + --topic=1 + volumes: + - ./worker-data:/data + working_dir: /data + depends_on: + - inference + - head + networks: + eth-model-local: + aliases: + - worker + ipv4_address: 172.22.0.10 + + head: + # 12D3KooWSBJucc8S3YdLH8n5UqTQpSbNjwEjcnYCW8zWuPhDAFHY + container_name: head-basic-eth-pred + image: 696230526504.dkr.ecr.us-east-1.amazonaws.com/allora-inference-base-head:latest + environment: + - HOME=/data + entrypoint: + - "/bin/bash" + - "-c" + - | + if [ ! -f /data/keys/priv.bin ]; then + echo "Generating new private keys..." + mkdir -p /data/keys + cd /data/keys + allora-keys + fi + allora-node --role=head --peer-db=/data/peerdb --function-db=/data/function-db \ + --runtime-path=/app/runtime --runtime-cli=bls-runtime --workspace=/data/workspace \ + --private-key=/data/keys/priv.bin --log-level=debug --port=9010 --rest-api=:6000 + ports: + - "6000:6000" + volumes: + - ./head-data:/data + working_dir: /data + networks: + eth-model-local: + aliases: + - head + ipv4_address: 172.22.0.100 + + +networks: + eth-model-local: + driver: bridge + ipam: + config: + - subnet: 172.22.0.0/24 + +volumes: + worker-data: + head-data: diff --git a/gunicorn_conf.py b/gunicorn_conf.py new file mode 100644 index 0000000..759df0b --- /dev/null +++ b/gunicorn_conf.py @@ -0,0 +1,12 @@ +# Gunicorn config variables +loglevel = "info" +errorlog = "-" # stderr +accesslog = "-" # stdout +worker_tmp_dir = "/dev/shm" +graceful_timeout = 120 +timeout = 30 +keepalive = 5 +worker_class = "gthread" +workers = 1 +threads = 8 +bind = "0.0.0.0:9000" diff --git a/main.py b/main.py new file mode 100644 index 0000000..4a6b890 --- /dev/null +++ b/main.py @@ -0,0 +1,25 @@ +import os +import requests +import sys +import json + +INFERENCE_ADDRESS = os.environ["INFERENCE_API_ADDRESS"] + + +def process(token_name): + response = requests.get(f"{INFERENCE_ADDRESS}/inference/{token_name}") + content = response.text + print(content) + + +if __name__ == "__main__": + # Your code logic with the parsed argument goes here + try: + if len(sys.argv) >= 2: + token_name = sys.argv[1] + else: + token_name = "ETH" + process(token_name=token_name) + except Exception as e: + response = json.dumps({"error": {str(e)}}) + print(response) diff --git a/model.py b/model.py new file mode 100644 index 0000000..2cea035 --- /dev/null +++ b/model.py @@ -0,0 +1,101 @@ +import os +import pickle +from zipfile import ZipFile +from datetime import datetime +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LinearRegression +from updater import download_binance_monthly_data, download_binance_daily_data +from config import app_base_path, model_file_path + + +binance_data_path = os.path.join(app_base_path, "binance/futures-klines") +training_price_data_path = os.path.join(app_base_path, "eth_price_data.csv") + + +def download_data(): + cm_or_um = "um" + symbols = ["ETHUSDT"] + intervals = ["1d"] + years = ["2020", "2021", "2022", "2023", "2024"] + months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"] + download_path = binance_data_path + download_binance_monthly_data( + cm_or_um, symbols, intervals, years, months, download_path + ) + print(f"Downloaded monthly data to {download_path}.") + current_datetime = datetime.now() + current_year = current_datetime.year + current_month = current_datetime.month + download_binance_daily_data( + cm_or_um, symbols, intervals, current_year, current_month, download_path + ) + print(f"Downloaded daily data to {download_path}.") + + +def format_data(): + files = sorted([x for x in os.listdir(binance_data_path)]) + + # No files to process + if len(files) == 0: + return + + price_df = pd.DataFrame() + for file in files: + zip_file_path = os.path.join(binance_data_path, file) + + if not zip_file_path.endswith(".zip"): + continue + + myzip = ZipFile(zip_file_path) + with myzip.open(myzip.filelist[0]) as f: + line = f.readline() + header = 0 if line.decode("utf-8").startswith("open_time") else None + df = pd.read_csv(myzip.open(myzip.filelist[0]), header=header).iloc[:, :11] + df.columns = [ + "start_time", + "open", + "high", + "low", + "close", + "volume", + "end_time", + "volume_usd", + "n_trades", + "taker_volume", + "taker_volume_usd", + ] + df.index = [pd.Timestamp(x + 1, unit="ms") for x in df["end_time"]] + df.index.name = "date" + price_df = pd.concat([price_df, df]) + + price_df.sort_index().to_csv(training_price_data_path) + + +def train_model(): + # Load the eth price data + price_data = pd.read_csv(training_price_data_path) + df = pd.DataFrame() + + # Convert 'date' to a numerical value (timestamp) we can use for regression + df["date"] = pd.to_datetime(price_data["date"]) + df["date"] = df["date"].map(pd.Timestamp.timestamp) + + df["price"] = price_data[["open", "close", "high", "low"]].mean(axis=1) + + # Reshape the data to the shape expected by sklearn + x = df["date"].values.reshape(-1, 1) + y = df["price"].values.reshape(-1, 1) + + # Split the data into training set and test set + x_train, _, y_train, _ = train_test_split(x, y, test_size=0.2, random_state=0) + + # Train the model + model = LinearRegression() + model.fit(x_train, y_train) + + # Save the trained model to a file + with open(model_file_path, "wb") as f: + pickle.dump(model, f) + + print(f"Trained model saved to {model_file_path}") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ae25853 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +flask[async] +gunicorn[gthread] +numpy==1.26.2 +pandas==2.1.3 +Requests==2.31.0 +scikit_learn==1.3.2 \ No newline at end of file diff --git a/update_app.py b/update_app.py new file mode 100644 index 0000000..0b3efd6 --- /dev/null +++ b/update_app.py @@ -0,0 +1,20 @@ +import os +import requests + +inference_address = os.environ["INFERENCE_API_ADDRESS"] +url = f"{inference_address}/update" + +response = requests.get(url) +if response.status_code == 200: + # Request was successful + content = response.text + + if content == "0": + print("Response content is '0'") + exit(0) + else: + exit(1) +else: + # Request failed + print(f"Request failed with status code: {response.status_code}") + exit(1) diff --git a/updater.py b/updater.py new file mode 100644 index 0000000..2eb4332 --- /dev/null +++ b/updater.py @@ -0,0 +1,54 @@ +import os +import requests +from concurrent.futures import ThreadPoolExecutor + + +# Function to download the URL, called asynchronously by several child processes +def download_url(url, download_path): + response = requests.get(url) + if response.status_code == 404: + print(f"File not exist: {url}") + else: + file_name = os.path.join(download_path, os.path.basename(url)) + + # create the entire path if it doesn't exist + os.makedirs(os.path.dirname(file_name), exist_ok=True) + + with open(file_name, "wb") as f: + f.write(response.content) + print(f"Downloaded: {url} to {file_name}") + + +def download_binance_monthly_data( + cm_or_um, symbols, intervals, years, months, download_path +): + # Verify if CM_OR_UM is correct, if not, exit + if cm_or_um not in ["cm", "um"]: + print("CM_OR_UM can be only cm or um") + return + base_url = f"https://data.binance.vision/data/futures/{cm_or_um}/monthly/klines" + + # Main loop to iterate over all the arrays and launch child processes + with ThreadPoolExecutor() as executor: + for symbol in symbols: + for interval in intervals: + for year in years: + for month in months: + url = f"{base_url}/{symbol}/{interval}/{symbol}-{interval}-{year}-{month}.zip" + executor.submit(download_url, url, download_path) + + +def download_binance_daily_data( + cm_or_um, symbols, intervals, year, month, download_path +): + if cm_or_um not in ["cm", "um"]: + print("CM_OR_UM can be only cm or um") + return + base_url = f"https://data.binance.vision/data/futures/{cm_or_um}/daily/klines" + + with ThreadPoolExecutor() as executor: + for symbol in symbols: + for interval in intervals: + for day in range(1, 32): # Assuming days range from 1 to 31 + url = f"{base_url}/{symbol}/{interval}/{symbol}-{interval}-{year}-{month:02d}-{day:02d}.zip" + executor.submit(download_url, url, download_path)