{"id":19427894,"url":"https://github.com/gappeah/binance-crypto-prediction-and-analysis","last_synced_at":"2025-02-25T05:22:39.458Z","repository":{"id":219180114,"uuid":"745713653","full_name":"gappeah/Binance-Crypto-Prediction-and-Analysis","owner":"gappeah","description":"This project leverages the Binance API to acquire real-time data for Bitcoin (BTC) and Ethereum (ETH). The data is then used to train a Long Short-Term Memory (LSTM) neural network model for predicting cryptocurrency prices.","archived":false,"fork":false,"pushed_at":"2024-05-20T20:22:15.000Z","size":615,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-05-20T23:06:01.650Z","etag":null,"topics":["api","binance","cryptocurrency","keras","machine-learning","neural-networks","python","tensorflow"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gappeah.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-19T23:51:22.000Z","updated_at":"2024-05-20T20:22:49.000Z","dependencies_parsed_at":"2024-01-25T22:33:28.078Z","dependency_job_id":"829050d0-255c-4f16-b555-e87ca02004f3","html_url":"https://github.com/gappeah/Binance-Crypto-Prediction-and-Analysis","commit_stats":null,"previous_names":["gappeah/crypto-ml","gappeah/cryptocurrency-price-prediction-with-lstm","gappeah/crypto-price-predict-lstm","gappeah/binance-crypto-prediction-and-analysis","gappeah/eth-to-btc-prediction-and-analysis-model"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gappeah%2FBinance-Crypto-Prediction-and-Analysis","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gappeah%2FBinance-Crypto-Prediction-and-Analysis/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gappeah%2FBinance-Crypto-Prediction-and-Analysis/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gappeah%2FBinance-Crypto-Prediction-and-Analysis/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gappeah","download_url":"https://codeload.github.com/gappeah/Binance-Crypto-Prediction-and-Analysis/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240607635,"owners_count":19828272,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","binance","cryptocurrency","keras","machine-learning","neural-networks","python","tensorflow"],"created_at":"2024-11-10T14:13:12.332Z","updated_at":"2025-02-25T05:22:39.373Z","avatar_url":"https://github.com/gappeah.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Binance Crypto Prediction and Analysis\n\nThis project demonstrates how to connect to the Binance API, retrieve real-time data for Bitcoin (BTC) and Ethereum (ETH), perform data preprocessing and visualization, and create a predictive model using Long Short-Term Memory (LSTM) neural networks. [Based on this tutorial](https://heartbeat.comet.ml/analyzing-and-creating-a-predictive-model-for-binance-data-69171dbd5bec \"Based on this tutorial\")\n\n# What is Bitcoin\n![Bitcoin svg](https://github.com/user-attachments/assets/521c9760-397a-4829-ad06-181704debe73)\n\nBitcoin is a decentralised digital currency that was introduced in 2009 by an anonymous person or group using the pseudonym Satoshi Nakamoto. It operates on a peer-to-peer network and utilizes blockchain technology to enable secure, transparent, and immutable transactions without the need for intermediaries like banks.\n\n## Bitcoin Blockchain Architecture\n\nBitcoin's blockchain is a distributed ledger that records all transactions across a network of computers (nodes). Each block in the chain contains a list of transactions, a timestamp, and a cryptographic hash of the previous block, ensuring that the data is securely linked. This structure prevents tampering, as altering any block would require changing all subsequent blocks, which is computationally infeasible due to the consensus mechanisms in place.\n\n### Example: Retrieving Block Information from Bitcoin's Blockchain\n\nYou can use the following code to retrieve information about a specific block from the Bitcoin blockchain using a public API:\n\n```python\nimport requests\n\n# Access Bitcoin's blockchain via a public API\nblock_hash = \"0000000000000000000e1f078b14e410ff19e215f50150b90ac89a8d1803e7d8\"\nurl = f\"https://blockchain.info/rawblock/{block_hash}\"\n\n# Fetch the block information\nresponse = requests.get(url)\n\nif response.status_code == 200:\n    block_data = response.json()\n    print(f\"Block Hash: {block_data['hash']}\")\n    print(f\"Block Height: {block_data['height']}\")\n    print(f\"Number of Transactions: {len(block_data['tx'])}\")\nelse:\n    print(\"Error fetching block data\")\n```\n\n---\n\n## Consensus Mechanism: Proof-of-Work (PoW)\n\nBitcoin employs a **Proof-of-Work (PoW)** consensus mechanism, where miners compete to solve complex mathematical problems to validate transactions and create new blocks. The first miner to solve the problem gets to add the new block to the blockchain and is rewarded with newly minted bitcoins and transaction fees. This process requires significant computational power and energy consumption.\n\n### Example: Simulating Bitcoin's Proof-of-Work\n\nThe following Python code simulates the Proof-of-Work process by attempting to find a hash that meets a certain difficulty level (leading zeros):\n\n```python\nimport hashlib\nimport time\n\ndef proof_of_work(prev_hash, transactions, difficulty):\n    nonce = 0\n    while True:\n        block_data = f\"{prev_hash}{transactions}{nonce}\".encode()\n        block_hash = hashlib.sha256(block_data).hexdigest()\n        \n        # Check if the hash meets the required difficulty\n        if block_hash.startswith('0' * difficulty):\n            return nonce, block_hash\n        nonce += 1\n\nprev_hash = \"0000000000000000000e1f078b14e410ff19e215f50150b90ac89a8d1803e7d8\"\ntransactions = \"Alice-\u003eBob-\u003e2BTC\"\ndifficulty = 5  # Number of leading zeros required in hash\n\nstart_time = time.time()\nnonce, valid_hash = proof_of_work(prev_hash, transactions, difficulty)\nend_time = time.time()\n\nprint(f\"Valid Hash: {valid_hash}\")\nprint(f\"Nonce: {nonce}\")\nprint(f\"Time taken: {end_time - start_time} seconds\")\n```\n\n---\n\n## Transaction Process\n\nWhen a user initiates a Bitcoin transaction, it is broadcast to the network. Miners collect these transactions into a block, and once the block is validated, it is added to the blockchain.\n\n### Example: Creating a Simple Bitcoin Transaction\n\nHere is how you can create and sign a Bitcoin transaction:\n\n```python\nfrom bitcoin import SelectParams\nfrom bitcoin.wallet import CBitcoinSecret, P2PKHBitcoinAddress\nfrom bitcoin.core import COIN\n\nSelectParams('mainnet')\n\n# Create private and public keys\nprivate_key = CBitcoinSecret('YourPrivateKeyHere')\naddress = P2PKHBitcoinAddress.from_pubkey(private_key.pub)\n\nprint(f'Bitcoin Address: {address}')\n\n# In practice, you'd create and broadcast a real transaction through a Bitcoin client.\n```\n\n---\n\n## Security Features\n\nBitcoin's security is based on strong cryptographic techniques such as **hash functions** and **digital signatures**. \n\n### Hash Functions\n\nBitcoin uses the **SHA-256** hashing algorithm to secure its blockchain. Each block's hash is generated based on its contents and the hash of the previous block, making the chain immutable.\n\n### Example: Generating a SHA-256 Hash\n\n```python\nimport hashlib\n\ndata = \"Hello, Bitcoin!\"\nhashed_data = hashlib.sha256(data.encode()).hexdigest()\n\nprint(f\"SHA-256 Hash: {hashed_data}\")\n```\n\n### Digital Signatures\n\nBitcoin transactions are signed using private keys. This ensures that only the owner of a Bitcoin address can authorize spending their bitcoins.\n\n### Example: Signing a Message with a Private Key\n\n```python\nfrom bitcoin.wallet import CBitcoinSecret\nfrom bitcoin.signmessage import BitcoinMessage, SignMessage\n\n# Create a private key\nprivate_key = CBitcoinSecret('YourPrivateKeyHere')\n\n# Create a message to sign\nmessage = BitcoinMessage('This is a secure message.')\n\n# Sign the message with the private key\nsignature = SignMessage(private_key, message)\n\nprint(f\"Signed Message: {signature}\")\n```\n\n## What is Ethereum \n![images](https://github.com/user-attachments/assets/9af1cd8b-f9ec-45fb-8e3e-69c382497165)\n* Ethereum is a decentralised, global platform that uses blockchain technology to enable the creation of digital applications and currencies.\n* It's known for its native cryptocurrency, ether (ETH), and is often mentioned alongside Bitcoin as a leader in the cryptocurrency and blockchain space. \n* Developers can build and deploy decentralised applications (DApps) through the use of smart contracts. It was proposed by Vitalik Buterin in 2013 and officially launched on July 30, 2015.\n\n### Blockchain Architecture\nEthereum operates on a blockchain, which is a distributed ledger technology that records transactions in a secure and immutable manner. Each block in the Ethereum blockchain contains a cryptographic hash of the previous block, creating a chain that ensures data integrity. This architecture allows for a decentralized network where no single entity has control over the entire blockchain.\n\n**Example: Interacting with Ethereum Blockchain to Get the Latest Block**\n\n```python\nfrom web3 import Web3\n\n# Connect to Ethereum node\nw3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'))\n\n# Check if connection is successful\nif w3.isConnected():\n    # Get latest block number\n    latest_block = w3.eth.blockNumber\n    print(f'Latest block number: {latest_block}')\nelse:\n    print('Failed to connect to Ethereum node')\n```\n\n---\n\n### Smart Contracts\nSmart contracts are self-executing contracts with the terms directly written into code. They run on the Ethereum Virtual Machine (EVM), which allows any code compatible with EVM to execute on the Ethereum network. Smart contracts facilitate, verify, or enforce the negotiation or performance of a contract without intermediaries, thus reducing costs and increasing efficiency.\n\n**Example: Simple Solidity Smart Contract**\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract SimpleStorage {\n    uint256 storedValue;\n\n    // Function to store a value\n    function store(uint256 _value) public {\n        storedValue = _value;\n    }\n\n    // Function to retrieve the stored value\n    function retrieve() public view returns (uint256) {\n        return storedValue;\n    }\n}\n```\n\n---\n\n### Ethereum Virtual Machine (EVM)\nThe EVM is a runtime environment for executing smart contracts and DApps on the Ethereum blockchain. It abstracts the underlying complexity of the network, allowing developers to write code in various programming languages that can be compiled into EVM bytecode. The EVM operates in a deterministic manner, ensuring that all nodes reach consensus on the state of the blockchain after executing transactions.\n\n**Example: Deploying Smart Contract using Ethers.js**\n\n```javascript\nconst { ethers } = require(\"ethers\");\n\nasync function deployContract() {\n    const provider = new ethers.providers.JsonRpcProvider(\"https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID\");\n    const wallet = new ethers.Wallet(\"YOUR_PRIVATE_KEY\", provider);\n\n    const abi = [ /* ABI from the compiled contract */ ];\n    const bytecode = \"0x...\"; // Compiled contract bytecode\n\n    const contractFactory = new ethers.ContractFactory(abi, bytecode, wallet);\n    const contract = await contractFactory.deploy();\n    console.log(\"Contract deployed at:\", contract.address);\n}\n\ndeployContract();\n```\n\n---\n\n### Consensus Mechanism\nEthereum transitioned from Proof-of-Work (PoW) to Proof-of-Stake (PoS) consensus with the \"Merge\" on September 15, 2022. In PoS, validators are chosen to create new blocks based on the amount of ETH they hold and are willing to \"stake\" as collateral.\n\n**Example: Setting up an Ethereum Validator for PoS (CLI)**\n\n```bash\n# Install eth2deposit-cli\npip install eth2deposit-cli\n\n# Generate new Ethereum 2.0 keys\neth2deposit-cli new-mnemonic --num_validators 1 --chain mainnet\n\n# Create the deposit\neth2deposit-cli generate-deposit --validator_keys /path/to/validator_keys --chain mainnet\n```\n\n---\n\n### Gas Fees\nTransactions on the Ethereum network require gas fees, paid in ETH. Gas serves as a measure of computational effort required to execute operations like transactions and smart contract executions.\n\n**Example: Sending a Transaction with Gas Fees using Web3.js**\n\n```javascript\nconst Web3 = require('web3');\nconst web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');\n\nconst tx = {\n    from: '0xYourAddress',\n    to: '0xRecipientAddress',\n    value: web3.utils.toWei('0.1', 'ether'), \n    gas: 21000, \n    gasPrice: web3.utils.toWei('100', 'gwei') \n};\n\nweb3.eth.accounts.signTransaction(tx, 'YOUR_PRIVATE_KEY')\n    .then(signedTx =\u003e web3.eth.sendSignedTransaction(signedTx.rawTransaction))\n    .then(receipt =\u003e console.log('Transaction successful:', receipt.transactionHash))\n    .catch(err =\u003e console.error('Error sending transaction:', err));\n```\n### Use Cases\nEthereum supports various applications across multiple domains:\n- **Decentralized Finance (DeFi)**: Platforms built on Ethereum allow users to lend, borrow, trade, and earn interest without traditional financial intermediaries.\n- **Non-Fungible Tokens (NFTs)**: Ethereum provides a framework for creating unique digital assets that represent ownership of specific items or content.\n- **Decentralized Autonomous Organizations (DAOs)**: These entities operate through smart contracts, allowing members to govern collectively without centralized control.\n\n# Visualising the results\n![output_1](https://github.com/user-attachments/assets/61a5e7c6-5240-4ad2-959d-2aa712490aa5)\n![output_2](https://github.com/user-attachments/assets/d06e7cab-9fe7-4961-8314-08b07bfb9207)\n![output](https://github.com/user-attachments/assets/6e18ff07-a8a2-4486-872e-1a8af86f3d21)\n\n## Prerequisites\n\nBefore running this project, ensure you have the following installed:\n\n- Python 3.x\n- Anaconda\n- Binance account (to obtain API key and secret)\n- Jupyter Notebook\n- Note: if you are having difficulties with installing Jupytyer Notebook on Visual Code Studio I recommend you watch [this video](https://www.youtube.com/watch?v=h1sAzPojKMg) which explains how to set up Jupytyer Notebook and Anaconda in less than 4 minutes.\n\n\n## Installation\n\n1. Clone the repository:\n\n```\ngit clone https://github.com/gappeah/Binance-Crypto-Prediction-and-Analysis.git\n```\n\n2. Navigate to the project directory:\n\n```\ncd Binance-Crypto-Prediction-and-Analysis\n```\n\n3. Install the required Python packages:\n\n```\npip install -r requirements.txt\n```\n\n4. Create a `config.ini` file in the project directory with your Binance API key and secret:\n\n```ini\n[binance]\napi_key = your_api_key\napi_secret = your_api_secret\n```\n\n## Usage\n\n1. Open the `binance_prediction.ipynb` Jupyter Notebook file.\n\n2. Run the notebook cells sequentially to execute the following steps:\n\n   - Import necessary libraries\n   - Configure and authenticate with the Binance API\n   - Retrieve and preprocess historical data for BTC and ETH\n   - Visualize the data using mplfinance\n   - Create an LSTM predictive model\n   - Test the model on a separate dataset\n   - Plot the actual and predicted prices\n\n## Files\n\n- `binance_prediction.ipynb`: Jupyter Notebook containing the main code\n- `config.ini`: Configuration file for storing Binance API key and secret (excluded from the repository)\n- `requirements.txt`: List of required Python packages\n\n## Contributing\n\nContributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.\n\n## Acknowledgments\n- [Python-Binance](https://python-binance.readthedocs.io/en/latest/) - The official Python library for the Binance API\n- [mplfinance](https://github.com/matplotlib/mplfinance) - Financial data visualization library for Python\n- [TensorFlow](https://www.tensorflow.org/) - Open-source machine learning framework\n- [Keras](https://keras.io/) - High-level neural networks API\n- [Anaconda](https://www.anaconda.com/) - Distribution of the Python and R\n- [NumPy](https://numpy.org/) -  A library that adds support for large, multi-dimensional arrays and matrices\n- [Pandas](https://pandas.pydata.org/) - A fast, powerful, flexible and easy to use open source data analysis for manipulating datasets\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgappeah%2Fbinance-crypto-prediction-and-analysis","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgappeah%2Fbinance-crypto-prediction-and-analysis","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgappeah%2Fbinance-crypto-prediction-and-analysis/lists"}