From 5ccc15ab52a6b4dd46704f227c4dd62e39a765ff Mon Sep 17 00:00:00 2001 From: Marc Mailloux Date: Wed, 17 Apr 2024 08:54:48 -0600 Subject: [PATCH 1/2] fixed bug, changed api url to be able to view all blocks, adjusted effort scaling for effort plot --- app.py | 11 +- block.csv => assets/block.csv | 0 export | 2 - front_appy.py | 186 - history.txt | 58201 ---------------- holder.py | 280 - .../__pycache__/front_page.cpython-310.pyc | Bin 0 -> 11738 bytes .../__pycache__/front_page_1.cpython-310.pyc | Bin 0 -> 11717 bytes .../__pycache__/front_page_1.cpython-312.pyc | Bin 17410 -> 17414 bytes .../__pycache__/mining_page.cpython-310.pyc | Bin 0 -> 9707 bytes .../__pycache__/mining_page_1.cpython-310.pyc | Bin 0 -> 9795 bytes .../__pycache__/mining_page_1.cpython-312.pyc | Bin 16780 -> 16950 bytes layouts/front_page.py | 109 +- layouts/front_page_1.py | 400 - layouts/mining_page.py | 305 +- layouts/mining_page_1.py | 300 - prototype-Copy1.ipynb | 1215 - prototype.ipynb | 44 +- prototype2.ipynb | 77 - response_df.csv | 5 - utils/__pycache__/api_reader.cpython-310.pyc | Bin 17489 -> 10873 bytes utils/__pycache__/api_reader.cpython-312.pyc | Bin 18341 -> 18345 bytes utils/__pycache__/dash_utils.cpython-310.pyc | Bin 0 -> 4203 bytes utils/__pycache__/dash_utils.cpython-312.pyc | Bin 5789 -> 5793 bytes utils/__pycache__/reader.cpython-310.pyc | Bin 0 -> 13963 bytes utils/__pycache__/reader.cpython-312.pyc | Bin 22966 -> 22985 bytes utils/api_reader.py | 8 +- utils/dash_utils.py | 1 - utils/reader.py | 484 - 29 files changed, 206 insertions(+), 61422 deletions(-) rename block.csv => assets/block.csv (100%) delete mode 100644 export delete mode 100644 front_appy.py delete mode 100644 history.txt delete mode 100644 holder.py create mode 100644 layouts/__pycache__/front_page.cpython-310.pyc create mode 100644 layouts/__pycache__/front_page_1.cpython-310.pyc create mode 100644 layouts/__pycache__/mining_page.cpython-310.pyc create mode 100644 layouts/__pycache__/mining_page_1.cpython-310.pyc delete mode 100644 layouts/front_page_1.py delete mode 100644 layouts/mining_page_1.py delete mode 100644 prototype-Copy1.ipynb delete mode 100644 prototype2.ipynb delete mode 100644 response_df.csv create mode 100644 utils/__pycache__/dash_utils.cpython-310.pyc create mode 100644 utils/__pycache__/reader.cpython-310.pyc delete mode 100644 utils/reader.py diff --git a/app.py b/app.py index 3a773676..be58ed36 100644 --- a/app.py +++ b/app.py @@ -1,13 +1,12 @@ # app.py from dash import Dash, html, dcc, Input, Output, State -from layouts import front_page_1, mining_page_1 +from layouts import front_page, mining_page from urllib.parse import quote, unquote import dash_bootstrap_components as dbc from utils.api_reader import SigmaWalletReader, PriceReader -from layouts.front_page_1 import setup_front_page_callbacks -# from layouts.main_page import setup_main_page_callbacks -from layouts.mining_page_1 import setup_mining_page_callbacks +from layouts.front_page import setup_front_page_callbacks +from layouts.mining_page import setup_mining_page_callbacks from flask_login import LoginManager, UserMixin, login_user from flask import Flask, request, session, redirect, url_for from flask_session import Session @@ -49,9 +48,9 @@ def display_page(pathname): mining_address = unquote(pathname.lstrip('/')) # Use the mining address to generate the page content # This is where you might call a function to get the layout based on the mining address - return mining_page_1.get_layout(reader) + return mining_page.get_layout(reader) else: - return front_page_1.get_layout(reader) + return front_page.get_layout(reader) # Define callback to update page content or handle business logic @app.callback( diff --git a/block.csv b/assets/block.csv similarity index 100% rename from block.csv rename to assets/block.csv diff --git a/export b/export deleted file mode 100644 index 4cacd711..00000000 --- a/export +++ /dev/null @@ -1,2 +0,0 @@ -export PATH="/usr/local/opt/python@3.9/bin:$PATH" - diff --git a/front_appy.py b/front_appy.py deleted file mode 100644 index 700567ec..00000000 --- a/front_appy.py +++ /dev/null @@ -1,186 +0,0 @@ -import dash -from dash import html, dcc -import dash_bootstrap_components as dbc -from utils.reader import SigmaWalletReader, PriceReader -price_reader = PriceReader() -sigma_reader = SigmaWalletReader(config_path="../conf") - -data = sigma_reader.get_front_page_data() - -# Pool Metrics -fee = 'Pool Fee: {}%'.format(data['fee']) -paid = 'Cumulative Payments: {}'.format(data['paid']) -blocks_found = 'Blocks Found: {}'.format(data['blocks']) -last_block = 'Last Block Found: {}'.format(data['last_block_found']) -effort= 'Current Pool Effort: {}'.format(data['pool_effort']) -min_payout = 'Minimum Payout: {}'.format(data['minimumPayment']) - -payout_schema = 'Pool Payout Schema: {}'.format(data['payoutScheme']) -n_miners = '{}'.format(data['connectedMiners']) -hashrate = '{} GH/s'.format(round(data['poolHashrate'], 3)) - -# Network Metrics -net_hashrate = 'Network Hashrate: {} TH/s'.format(data['networkHashrate']) -difficulty = 'Network Difficulty: {}P'.format(round(data['networkDifficulty'], 3)) -net_block_found = 'Last Block Found on Network: {}'.format(data['lastNetworkBlockTime']) -height = 'Height: {}'.format(data['blockHeight']) - -image_style = {'height': '48px', 'marginRight': '10px',} -icon_text_style={'display': 'flex', 'alignItems': 'center', 'justifyContent': 'flex-start', 'color': 'white', 'padding': '10px', 'marginBottom': '10px'} - - -def create_image_text_block(image, text): - cell = html.Div(style=metric_row_style, children=[ - html.Img(src='assets/{}'.format(image), style=image_style), - html.Span(text, style={'padding': '10px'}) - ]) - return cell -# Style for the card containers -card_style = { - 'backgroundColor': '#333333', - 'color': 'white', - 'marginBottom': '25px', - 'padding': '25px', -} - -# Style for the metric rows inside the cards -metric_row_style = { - 'display': 'flex', - 'alignItems': 'center', - 'justifyContent': 'flex-start', -} - -image_style = {'height': '24px'} - -# Initialize the Dash app with Bootstrap CSS -app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) - -app.layout = dbc.Container(fluid=True, style={'backgroundColor': '#1e1e1e', 'padding': '10px', 'justifyContent': 'center', 'fontFamily': 'sans-serif'}, - children=[html.H1('ERGO Sigmanaut Mining Pool', style={'color': '#FFA500', 'textAlign': 'center',}), - # Metrics overview row - dbc.Row(justify='center', style={'padding': '20px'}, children=[ - dbc.Col(dbc.Card(style=card_style, children=[ - html.Img(src='assets/mining_temp.png', style={'height': '75px'}), - html.H2(hashrate, style={'color': '#FFA500'}), - html.P("Hashrate")]), - width=3, lg=3, className="px-2", style={'marginRight': '5px', 'marginLeft': '5px'}), - - dbc.Col(dbc.Card(style=card_style, children=[ - html.Img(src='assets/mining_temp.png', style={'height': '75px'}), - html.H2(n_miners, style={'color': '#FFA500'}), - html.P("Miners") - ]), width=3, lg=3, style={'marginRight': '5px', 'marginLeft': '5px'}), - - dbc.Col(dbc.Card(style=card_style, children=[ - html.Img(src='assets/mining_temp.png', style={'height': '75px'}), - html.H2('$1.9', style={'color': '#FFA500'}), - html.P("Price") - ]), width=3, lg=3, md=6,style={'marginRight': '5px', 'marginLeft': '5px'}), - - ]), - # Detailed stats - dbc.Row(justify='center', style={'padding': '20px'}, children=[ - dbc.Col(md=6, children=[ - dbc.Card(style=card_style, children=[ - html.H3('Pool Stats', style={'color': '#FFA500', 'fontWeight': 'bold'}), - create_image_text_block('mining_temp.png', 'Algo: Autolykos V2'), - create_image_text_block('mining_temp.png', 'Current Reward: 30'), - # create_image_text_block('mining_temp.png', 'Price: $1.9'), - create_image_text_block('mining_temp.png', paid), - create_image_text_block('mining_temp.png', payout_schema), - create_image_text_block('mining_temp.png', min_payout), - ]) - ]), - - dbc.Col(md=6, children=[ - dbc.Card(style=card_style, children=[ - html.H3('Network Stats', style={'color': '#FFA500', 'fontWeight': 'bold'}), - - create_image_text_block('mining_temp.png', difficulty), - create_image_text_block('mining_temp.png', net_block_found), - create_image_text_block('mining_temp.png', height), - - ]) - ]), - ]), - - # Start Mining Button - dbc.Row(justify='center', children=[ - html.Button('Start Mining ⛏️', id='start-mining-button', style={ - 'marginTop': '20px', - 'backgroundColor': '#FFA500', - 'border': 'none', - 'padding': '10px 20px', - 'color': 'white', - 'fontSize': '20px', - 'borderRadius': '5px' - }) - ]), - - # Mining Address Input - dbc.Row(justify='center', children=[ - dbc.Col(md=8, children=[ - dcc.Input(id='mining-address-input', type='text', placeholder='Mining Address', style={ - 'width': '100%', - 'padding': '10px', - 'marginTop': '20px', - 'marginBottom': '50px', - 'borderRadius': '5px' - }), - ]) - ]), - html.H1('CONNECTING TO THE POOL', style={'color': '#FFA500', 'textAlign': 'center',}), - - # Column for the markdown - html.Div(children=[ - dcc.Markdown(''' - ## Choose A Port - Based on your hashrate and TLS specificity choose the port that is right for you. - - - Port 3052 - Lower than 10GH/s - No TLS - - Port 3053 - Higher than 10GH/s - No TLS - - Port 3054 - Lower than 10GH/s - TLS - - Port 3055 - Higher than 10GH/s - TLS - - ### Connecting to the Pool - The pools url is 15.204.211.130 - - So if you want TLS and under 10GH/s the port you would choose is 3054 and so on - - #### HIVEOS - 1. Set "Pool URL" to 15.204.211.130:3054 - - #### MMPOS - 1. Modify an existing or create a new pool in Management - 2. In Hostname enter the URL: 15.204.211.130 - 3. Port: 3054 - - #### Linux or Windows - 1. Edit the .sh file for the specific miner, in this case lolminer - 2. In the pool argument enter the full url with port of choice - ``` - POOL=15.204.211.130:3054 - WALLET=.QX-Fan-Club - ./lolMiner --algo AUTOLYKOS2 --pool $POOL --user $WALLET $@ - while [ $? -eq 42 ]; do - sleep 10s - ./lolMiner --algo AUTOLYKOS2 --pool $POOL --user $WALLET $@ - done - ``` - - ## Updating the Dashboard from git - ``` - docker compose pull # pulls the latest docker image - docker compose up -d # Runs the UI - docker compose down # Stops the UI - ``` - - Shout out to Vipor.Net for the dashboard inspiration! - ''') - ],style={'backgroundColor': '#333333', 'color': 'white', 'padding': '20px', 'code': {'color': '#333333'}}), - - -]) - -if __name__ == '__main__': - app.run_server(debug=True) \ No newline at end of file diff --git a/history.txt b/history.txt deleted file mode 100644 index 448b1a7e..00000000 --- a/history.txt +++ /dev/null @@ -1,58201 +0,0 @@ - 2/1: import torch - 2/2: torch.cuda.is_available() - 3/1: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 5/1: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 5/2: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/1: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/2: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/3: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/4: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/5: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/6: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/7: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/8: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') - 7/9: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') -7/10: runfile('/home/whaleshark/.config/spyder-py3/temp.py', wdir='/home/whaleshark/.config/spyder-py3') -12/1: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -12/2: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -12/3: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -12/4: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/1: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/2: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/3: processed_data.columns -18/4: processed_data.head() -18/5: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/6: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/7: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/8: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/9: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/10: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/11: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/12: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/13: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/14: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/15: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/16: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -18/17: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/1: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/2: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/3: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -22/1: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/4: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -22/2: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/5: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/6: runfile('/home/whaleshark/Documents/git/whale-shark/create_dataloader.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/7: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/8: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/9: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/10: runfile('/home/whaleshark/Documents/git/whale-shark/train.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/11: filtered_df -20/12: runfile('/home/whaleshark/Documents/git/whale-shark/features.py', wdir='/home/whaleshark/Documents/git/whale-shark') -20/13: filtered_df['Next_Candle_Color'].unique() -20/14: z = filtered_df[filtered_df['Next_Candle_Color'] == 0] -20/15: x = filtered_df[filtered_df['Next_Candle_Color'] == 1] -20/16: len(z) / len(filtered_df) -20/17: len(x) / len(filtered_df) -24/1: -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -24/2: import whaleshark -24/3: import whale-shark -24/4: import 'whale-shark' -24/5: import pipeline -24/6: -import sys -sys.path.append(' ') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -24/7: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -24/8: import pipeline -24/9: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from datetime import datetime, timedelta -24/10: -# First lets pull the data -fetcher = CoinbaseDataFetcher(api_key, api_secret) -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -granularity = 3600 #300 # 5-minute intervals # 900 # 15-minute intervals - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -24/11: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -granularity = 3600 #300 # 5-minute intervals # 900 # 15-minute intervals - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -24/12: -# Now lets shape those features -file = 'data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(True) - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -24/13: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(True) - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -24/14: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(True) - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -24/15: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders() - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -24/16: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from datetime import datetime, timedelta -import torch -24/17: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders() - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -24/18: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from pieline.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -24/19: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from pipeline.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -24/20: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -24/21: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -24/22: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -granularity = 3600 #300 # 5-minute intervals # 900 # 15-minute intervals - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -24/23: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(True) - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -24/24: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders() - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -24/25: -# Now we can train the model! -model = EnhancedNN(n_features=17) -trainer = ModelTrainer(model, 'data') -trainer.train() -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -24/26: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -granularity = 3600 #300 # 5-minute intervals # 900 # 15-minute intervals - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -25/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -25/2: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -25/3: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 300 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -25/4: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -25/5: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 300 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -26/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -26/2: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 300 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -26/3: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -26/4: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -26/5: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 300 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -27/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -27/2: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 300 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -27/3: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -27/4: -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) -print('Number of samples: {}'.format(len(data))) -27/5: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -29/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -29/2: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131202-20231130.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -29/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -29/4: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -29/5: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = 'pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -29/6: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='Next_Candle_Color') -print(filtered_df.columns) -29/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -29/8: -# Now we can train the model! -model = EnhancedNN(n_features=17) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -29/9: -# Now we can train the model! -model = EnhancedNN(n_features=18) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -29/10: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -29/11: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -29/12: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -29/13: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label' - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -29/14: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -29/15: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -29/16: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label' - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -29/17: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -31/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -31/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -31/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -31/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -33/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -33/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -33/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -33/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2064) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -33/5: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -33/6: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -33/7: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -33/8: -# Now we can train the model! -model = SimpleNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -33/9: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=False) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -33/10: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -33/11: -# Now we can train the model! -model = SimpleNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -35/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -35/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=False) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -35/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -35/5: -# Now we can train the model! -model = SimpleNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/6: -# Now we can train the model! -model = SimpleNN(n_features=17) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/7: -# Now we can train the model! -model = SimpleNN(n_features=3) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/8: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns) -35/9: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -35/10: -# Now we can train the model! -model = SimpleNN(n_features=3) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/11: -# Now we can train the model! -model = SimpleNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -35/12: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -#processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns) -36/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -36/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -36/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -#processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns) -38/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -38/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -38/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -#processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns) -38/4: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -#processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -38/5: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -38/6: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -38/7: -# Now we can train the model! -model = SimpleNN(n_features=len(filtered_df.columns)) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -38/8: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - print(inputs, labels) - break -38/9: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -38/10: -# Now we can train the model! -model = SimpleNN(n_features=17 -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -38/11: -# Now we can train the model! -model = SimpleNN(n_features=17) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -38/12: filtered_df.label.unique() -40/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -40/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -40/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -40/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -40/5: -# Now we can train the model! -model = SimpleNN(n_features=17, len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -40/6: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -42/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -42/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -42/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -42/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -42/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique()), device='cpu') -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -42/6: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -44/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -44/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -44/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -44/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -44/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -46/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -46/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -46/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -46/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -46/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -47/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -47/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -47/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -47/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -47/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -49/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -50/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -52/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -52/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -52/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -52/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -52/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -54/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -54/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -54/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -54/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -54/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -56/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -56/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -56/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -56/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -56/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -56/6: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50,) # device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -56/7: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -58/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -58/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -58/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -58/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -58/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -59/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -59/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -59/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -59/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -59/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -59/6: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -59/7: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique())) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -59/8: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -64/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -64/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -64/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -64/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1032) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -64/5: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=50, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -64/6: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=500, device='cpu') -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -64/7: -# Now we can train the model! -model = SimpleNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=500) -trainer.train(accuracy_threshold=0.6) -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -64/8: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) - -trainer.get_time() -65/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -65/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -65/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -65/4: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2048) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -65/5: -# Now we can train the model! -model = EnhancedNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -65/6: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -65/7: -c1 = filtered_df[filtered_df.label == 0] -c1 = filtered_df[filtered_df.label == 0] -65/8: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df)) -65/9: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -66/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -66/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -66/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -66/4: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -66/5: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2048) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -66/6: -# Now we can train the model! -model = EnhancedNN(n_features=17, n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -66/7: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -66/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -67/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -67/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -67/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -67/4: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -67/5: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2048) - -loaders = runner.create_dataloaders(test_size=0.4, - val_size=0.4, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -67/6: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -67/7: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -67/8: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -67/9: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -67/10: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -67/11: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -67/12: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -67/13: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -68/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -68/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -68/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -68/4: processed_data.head() -68/5: processed_data.columns -69/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -69/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -69/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -69/4: processed_data.columns -69/5: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -69/6: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -69/7: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -69/8: processed_data.head() -70/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -70/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -70/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -70/4: processed_data.head() -70/5: processed_data.columns -70/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -70/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -70/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -70/9: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -70/10: processed_data.dropna() -70/11: processed_data.dropna().to_string() -70/12: processed_data.dropna().columns() -70/13: processed_data.dropna().columns -71/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -71/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -71/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -71/4: processed_data.columns -71/5: processed_data.dropna().columns -71/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -71/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -71/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -71/9: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -72/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -72/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -72/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -72/4: processed_data.columns -72/5: processed_data.dropna().columns -72/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -72/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -72/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -72/9: -test_loss, test_accuracy = trainer.evaluate_model(trainer.test_loader) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -73/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -73/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -73/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -73/4: processed_data.columns -73/5: processed_data.dropna().columns -73/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -73/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -73/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -74/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -74/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -74/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -74/4: processed_data.columns -74/5: processed_data.dropna().columns -74/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -74/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -74/8: -# Now we can train the model! -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=len(filtered_df.label.unique())) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -75/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -75/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -75/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -75/4: processed_data.columns -75/5: processed_data.dropna().columns -75/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -75/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -75/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6) -trainer.get_time() -76/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -76/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -76/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -76/4: processed_data.columns -76/5: processed_data.dropna().columns -76/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -76/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -76/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=num_classes) -trainer.get_time() -76/9: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -78/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -78/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -78/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -78/4: processed_data.columns -78/5: processed_data.dropna().columns -78/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -78/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -78/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -80/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 - -from datetime import datetime, timedelta -import torch -80/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -80/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -80/4: processed_data.columns -80/5: processed_data.dropna().columns -80/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -80/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -80/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -80/9: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -80/10: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -80/11: confusion_matrix -80/12: -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np - -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() -80/13: plot_confusion_matrix(confusion_matrix, [0, 1, 2, 3, 4] -80/14: -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np - -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() -80/15: plot_confusion_matrix(confusion_matrix, [0, 1, 2, 3, 4]) -80/16: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, [0, 1, 'neutral', 3, 4]) -80/17: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -80/18: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -80/19: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -80/20: confusion_matrix -80/21: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -80/22: confusion_matrix -82/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -84/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -84/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -84/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -84/4: processed_data.columns -84/5: processed_data.dropna().columns -84/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -84/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -84/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -85/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -85/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -85/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -85/4: processed_data.columns -85/5: processed_data.dropna().columns -85/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -85/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -85/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -87/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -87/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -87/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -87/4: processed_data.columns -87/5: processed_data.dropna().columns -87/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -87/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -87/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -88/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -88/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -88/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -88/4: processed_data.columns -88/5: processed_data.dropna().columns -88/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -88/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -88/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -90/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -90/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -90/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -90/4: processed_data.columns -90/5: processed_data.dropna().columns -90/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -90/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -90/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -92/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -92/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -92/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -92/4: processed_data.columns -92/5: processed_data.dropna().columns -92/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -92/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=4125) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -92/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -92/9: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -92/10: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -93/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -93/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -93/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -93/4: processed_data.columns -93/5: processed_data.dropna().columns -93/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -93/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -93/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -94/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -94/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -94/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -94/4: processed_data.columns -94/5: processed_data.dropna().columns -94/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -94/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -94/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -94/9: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1024) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -94/10: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=100) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -94/11: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -94/12: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -94/13: confusion_matrix -94/14: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -94/15: confusion_matrix -94/16: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -94/17: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -94/18: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -94/19: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -94/20: confusion_matrix -94/21: -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -94/22: confusion_matrix -94/23: confusion_matrix[0] -94/24: confusion_matrix -94/25: np.array(confusion_matrix) -94/26: -confusion_matrix = np.array(confusion_matrix) -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -95/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -95/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -95/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -95/4: processed_data.columns -95/5: processed_data.dropna().columns -95/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -95/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -95/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -96/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -96/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -96/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -96/4: processed_data.columns -96/5: processed_data.dropna().columns -96/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -96/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -96/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhacedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -96/9: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -96/10: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -96/11: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -96/12: -confusion_matrix = np.array(confusion_matrix) -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -97/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -97/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -97/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -97/4: processed_data.columns -97/5: processed_data.dropna().columns -97/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -97/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -97/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -97/9: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -97/10: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -97/11: -confusion_matrix = np.array(confusion_matrix) -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -97/12: -confusion_matrix = np.array(confusion_matrix) -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -98/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -98/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -98/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -98/4: processed_data.columns -98/5: processed_data.dropna().columns -98/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -98/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -98/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -99/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -99/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -99/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -99/4: processed_data.columns -99/5: processed_data.dropna().columns -99/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -99/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -99/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=20) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -102/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -102/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -102/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -102/4: processed_data.columns -102/5: processed_data.dropna().columns -102/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -102/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -102/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=2) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -103/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -103/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -103/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -103/4: processed_data.columns -103/5: processed_data.dropna().columns -103/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -103/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -103/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=2) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -105/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -105/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -105/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -105/4: processed_data.columns -105/5: processed_data.dropna().columns -105/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -105/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -105/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=2) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -107/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -107/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -107/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -107/4: processed_data.columns -107/5: processed_data.dropna().columns -107/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -107/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -107/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=2) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -107/9: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -107/10: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -107/11: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -# trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -107/12: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -107/13: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -109/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -109/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -109/3: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -#file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -109/4: processed_data.columns -109/5: processed_data.dropna().columns -109/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -109/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -109/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.0001, epochs=2) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -109/9: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -109/10: -def plot_confusion_matrix(confusion_matrix, class_names): - """ - Plots a confusion matrix using Seaborn's heatmap. - - :param confusion_matrix: A 2D array of shape (num_classes, num_classes) representing the confusion matrix. - :param class_names: A list of class names, ordered according to their index in the confusion matrix. - """ - plt.figure(figsize=(10, 8)) - sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap='Blues', - xticklabels=class_names, yticklabels=class_names) - - plt.ylabel('True Label') - plt.xlabel('Predicted Label') - plt.title('Confusion Matrix') - plt.show() - -plot_confusion_matrix(confusion_matrix, ['really down', 'slightly down', 'neutral', 'slighty up', 'really up']) -109/11: -confusion_matrix = np.array(confusion_matrix) -correct_predictions = np.trace(confusion_matrix) -total_predictions = np.sum(confusion_matrix) -accuracy = correct_predictions / total_predictions - -print("Accuracy:", accuracy) -109/12: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.001, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -109/13: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -109/14: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -109/15: -# Now lets shape those features -file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -109/16: processed_data.columns -109/17: processed_data.dropna().columns -109/18: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -109/19: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=64) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -109/20: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -109/21: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1024) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -109/22: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -109/23: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -110/1: -import sys -sys.path.append('../') -from pipeline.coinbase_fetcher import CoinbaseDataFetcher -from pipeline.features import FeatureEngineer -from pipeline.create_dataloader import DataLoaderCreator -from pipeline.train import ModelTrainer -from models.simple_model import SimpleNN, EnhancedNN, resnet18 -from models.time_series_model import StockClassifier - -from datetime import datetime, timedelta -import torch -import matplotlib.pyplot as plt -import seaborn as sns -import numpy as np -110/2: -# DO we want new data? -fetch = False - -# First lets pull the data -fetcher = CoinbaseDataFetcher('', '') -pair = 'BTC-USD' -years = 10 -start_time = datetime.utcnow() - timedelta(days=365 * years) # Start from one year ago -end_time = datetime.utcnow() -#300-> 5-minute, 900-> 15-minute, 3600-> 1 hour -granularity = 900 - -# The filename where the CSV will be saved -filename = '10_year_long_historical_data.csv' - -# Fetch and save data as CSV -if fetch: - data = fetcher.get_data_as_csv(pair, start_time, end_time, granularity, filename) - print('Number of samples: {}'.format(len(data))) -110/3: -# Now lets shape those features -# file = '../data/BTC/USD/BTC_USD_60min_20131202-20231130.csv' # or a DataFrame -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -engineer = FeatureEngineer(file) -processed_data = engineer.get_processed_data(save=True) # we can turn save off if we plan to use filtered data - -filtered_df = engineer.select_features_based_on_correlation(label='label') -print(filtered_df.columns, len(filtered_df.columns)) -110/4: processed_data.columns -110/5: processed_data.dropna().columns -110/6: -ls = [] -for i in range(0, 5): - temp = filtered_df[filtered_df.label == i] - ls.append(temp) - print('For the class {} we have {} number of rows or {}% of the entire dataset'.format(i, len(temp), len(temp)/len(filtered_df))) -110/7: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=1024) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -110/8: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -110/9: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -110/10: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -110/11: -# Now we can create a Dataloader -runner = DataLoaderCreator('../data/filtered_engineered_data.csv', - batch_size=2048) - -loaders = runner.create_dataloaders(test_size=0.2, - val_size=0.2, label='label', - save_path='../data') - -train_data = torch.load('../data/train_loader.pth') -test_data = torch.load('../data/test_loader.pth') - -for inputs, labels in train_data: - print(inputs.shape, labels.shape) # Just for checking - break -110/12: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = EnhancedNN(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -110/13: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -110/14: -# Now we can train the model! -n_classes=len(filtered_df.label.unique()) -model = StockClassifier(n_features=len(filtered_df.columns), n_classes=n_classes) -print('number of classes: {}'.format(len(filtered_df.label.unique()))) -trainer = ModelTrainer(model, '../data', - learning_rate=0.01, epochs=10) -trainer.train(accuracy_threshold=0.6, num_classes=n_classes) -trainer.get_time() -110/15: -test_loss, test_accuracy, confusion_matrix = trainer.evaluate_model(trainer.test_loader, n_classes) -trainer.plot_confusion_matrix(confusion_matrix) -print('the Model achieved {} in testing accuracy'.format(test_accuracy)) -trainer.get_time() -110/16: -plt.scatter(processed_data.index, processed_data['Close'], c=df['label'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -110/17: -plt.scatter(processed_data.index, processed_data['Close'], c=processed_data['label'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -110/18: -plt.scatter(processed_data.index, processed_data['Close'], c=processed_data['future_price'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -110/19: -plt.scatter(processed_data.index, processed_data['Close'], c=processed_data['Candle_Color'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -110/20: -plt.scatter(processed_data.index, processed_data['Close'], c=processed_data['Trend'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -110/21: -plt.scatter(processed_data.index, processed_data['Close'], c=processed_data['label'], cmap='viridis') -plt.colorbar(label='Color scale') # Show color scale -plt.xlabel('X axis (Index)') -plt.ylabel('Y axis') -plt.title('Scatter Plot with Colored Points') -plt.show() -116/1: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/2: !pip install plotly -116/3: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/4: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/5: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/6: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/7: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/8: df -116/9: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/10: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/11: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -116/12: runfile('/home/whaleshark/Documents/git/whale-shark/trade_tools/trading_projections.py', wdir='/home/whaleshark/Documents/git/whale-shark/trade_tools') -118/1: -import ccxt -import pandas as pd -from mlforecast.core import TimeSeries -from mlforecast.forecast import Forecast -from lightgbm import LGBMRegressor - -# Fetch historical data from Coinbase -def fetch_data(symbol, timeframe, since): - exchange = ccxt.coinbasepro() - ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since) - df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) - df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') - df.set_index('timestamp', inplace=True) - return df - -# Main forecasting function -def forecast_bitcoin(): - # Fetch BTC data - btc_data = fetch_data('BTC/USD', '1d', '2020-01-01T00:00:00Z') - - # Prepare data for forecasting - btc_data.reset_index(inplace=True) - btc_data['symbol'] = 'BTC' - ts = TimeSeries(date_col='timestamp', id_col='symbol', y_col='close') - - # Split data - train_df, test_df = ts.split(btc_data, test_size=0.2) - - # Define and train model - params = {'n_estimators': 100, 'learning_rate': 0.1} - model = LGBMRegressor(**params) - fcst = Forecast(model, freq='D') - fcst.fit(train_df) - - # Make predictions - predictions = fcst.predict(test_df.index.levels[1].max()) - - return predictions - -# Run the forecasting function -forecast_results = forecast_bitcoin() -print(forecast_results) -120/1: -import ccxt -import pandas as pd -from mlforecast.core import TimeSeries -from mlforecast.forecast import Forecast -from lightgbm import LGBMRegressor - -# Fetch historical data from Coinbase -def fetch_data(symbol, timeframe, since): - exchange = ccxt.coinbasepro() - ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since) - df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) - df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') - df.set_index('timestamp', inplace=True) - return df - -# Main forecasting function -def forecast_bitcoin(): - # Fetch BTC data - btc_data = fetch_data('BTC/USD', '1d', '2020-01-01T00:00:00Z') - - # Prepare data for forecasting - btc_data.reset_index(inplace=True) - btc_data['symbol'] = 'BTC' - ts = TimeSeries(date_col='timestamp', id_col='symbol', y_col='close') - - # Split data - train_df, test_df = ts.split(btc_data, test_size=0.2) - - # Define and train model - params = {'n_estimators': 100, 'learning_rate': 0.1} - model = LGBMRegressor(**params) - fcst = Forecast(model, freq='D') - fcst.fit(train_df) - - # Make predictions - predictions = fcst.predict(test_df.index.levels[1].max()) - - return predictions - -# Run the forecasting function -forecast_results = forecast_bitcoin() -print(forecast_results) -120/2: -import ccxt -import pandas as pd -from mlforecast.core import TimeSeries -from mlforecast.forecast import Forecast -from lightgbm import LGBMRegressor - -# Fetch historical data from Coinbase -def fetch_data(symbol, timeframe, since): - exchange = ccxt.coinbasepro() - ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since) - df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) - df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') - df.set_index('timestamp', inplace=True) - return df - -# Main forecasting function -def forecast_bitcoin(): - # Fetch BTC data - btc_data = fetch_data('BTC/USD', '1d', '2020-01-01T00:00:00Z') - - # Prepare data for forecasting - btc_data.reset_index(inplace=True) - btc_data['symbol'] = 'BTC' - ts = TimeSeries(date_col='timestamp', id_col='symbol', y_col='close') - - # Split data - train_df, test_df = ts.split(btc_data, test_size=0.2) - - # Define and train model - params = {'n_estimators': 100, 'learning_rate': 0.1} - model = LGBMRegressor(**params) - fcst = Forecast(model, freq='D') - fcst.fit(train_df) - - # Make predictions - predictions = fcst.predict(test_df.index.levels[1].max()) - - return predictions - -# Run the forecasting function -forecast_results = forecast_bitcoin() -print(forecast_results) -120/3: -import ccxt -import pandas as pd -from mlforecast.core import TimeSeries -from mlforecast.forecast import Forecast -from lightgbm import LGBMRegressor - -# Fetch historical data from Coinbase -def fetch_data(symbol, timeframe, since): - exchange = ccxt.coinbasepro() - ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since) - df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) - df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') - df.set_index('timestamp', inplace=True) - return df - -# Main forecasting function -def forecast_bitcoin(): - # Fetch BTC data - btc_data = fetch_data('BTC/USD', '1d', '2020-01-01T00:00:00Z') - - # Prepare data for forecasting - btc_data.reset_index(inplace=True) - btc_data['symbol'] = 'BTC' - ts = TimeSeries(date_col='timestamp', id_col='symbol', y_col='close') - - # Split data - train_df, test_df = ts.split(btc_data, test_size=0.2) - - # Define and train model - params = {'n_estimators': 100, 'learning_rate': 0.1} - model = LGBMRegressor(**params) - fcst = Forecast(model, freq='D') - fcst.fit(train_df) - - # Make predictions - predictions = fcst.predict(test_df.index.levels[1].max()) - - return predictions - -# Run the forecasting function -forecast_results = forecast_bitcoin() -print(forecast_results) -120/4: -import random - -import pandas as pd -from datasetsforecast.m4 import M4 -from utilsforecast.plotting import plot_series -120/5: -import random - -import pandas as pd -from datasetsforecast.m4 import M4 -from utilsforecast.plotting import plot_series -120/6: -await M4.async_download('data', group='Hourly') -df, *_ = M4.load('data', 'Hourly') -uids = df['unique_id'].unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = df[df['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df -120/7: fig = plot_series(df, max_insample_length=24 * 14) -120/8: -fig = plot_series(df, max_insample_length=24 * 14) -fig -120/9: -from mlforecast import MLForecast -from mlforecast.target_transforms import Differences - -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(df) -prep -120/10: -fig = plot_series(prep) -fig -120/11: -fcst = MLForecast( - models=[], - freq=1, - lags=[1, 24], - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(df) -prep -120/12: prep.drop(columns=['unique_id', 'ds']).corr()['y'] -120/13: import lightgbm as lgb -120/14: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -120/15: -import lightgbm as lgb -from numba import njit -from window_ops.expanding import expanding_mean -from window_ops.rolling import rolling_mean -120/16: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -120/17: -import lightgbm as lgb -from numba import njit -from window_ops.expanding import expanding_mean -from window_ops.rolling import rolling_mean - -def hour_index(times): - return times % 24 -120/18: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -120/19: MLForecast(models=[avg, q75, q25], freq=1, lag_features=['lag1', 'lag24', 'expanding_mean_lag1', 'rolling_mean_lag24_window_size48'], date_features=[], num_threads=1) -120/20: MLForecast(models=[avg, q75, q25], freq=1, lag_features=['lag1', 'lag24', 'expanding_mean_lag1', 'rolling_mean_lag24_window_size48'], date_features=[], num_threads=1) -120/21: -preds = fcst.predict(48) -preds -120/22: -preds = fcst.predict(48) -preds -120/23: fig = plot_series(df, preds, max_insample_length=24 * 7) -120/24: -fig = plot_series(df, preds, max_insample_length=24 * 7) -fig -120/25: -fcst = MLForecast( - models=lgb.LGBMRegressor(**lgb_params), - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -cv_result = fcst.cross_validation( - df, - n_windows=4, # number of models to train/splits to perform - h=48, # length of the validation set in each window -) -cv_result -120/26: -fig = plot_series(cv_result, cv_result.drop(columns='cutoff'), max_insample_length=0) -fig -122/1: import pandas as pd -122/2: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -122/3: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -data -122/4: plot_series(data, max_insample_length=24 * 14) -122/5: -import pandas as pd -from utilsforecast.plotting import plot_series -122/6: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -data -122/7: plot_series(data, max_insample_length=24 * 14) -122/8: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -uids = data['unique_id'].unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df? -122/9: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -uids = data['unique_id'].unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df -122/10: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -uids = data.index.unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df -122/11: -import pandas as pd -from utilsforecast.plotting import plot_series -import random -122/12: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -uids = data.index.unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df -122/13: plot_series(data, max_insample_length=24 * 14) -122/14: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -data['unique_id'] = [item for item in data.index] -uids = data.index.unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['ds'].astype('int64') -df -122/15: -file = '../pipeline/data/BTC/USD/BTC_USD_5min_20131203-20231201.csv' -data = pd.read_csv(file) -data.columns, data.head() -122/16: - -data['unique_id'] = [item for item in data.index] -uids = data.index.unique() -random.seed(0) -sample_uids = random.choices(uids, k=4) -df = data[data['unique_id'].isin(sample_uids)].reset_index(drop=True) -df['ds'] = df['Time'].astype('int64') -df -124/1: -import pandas as pd -import yfinance as yf - -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -124/2: -import pandas as pd -import yfinance as yf - -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -124/3: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() -124/4: -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split - -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) - -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/5: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -124/6: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -124/7: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() -124/8: - - -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) - -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/9: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -124/10: btc_data -124/11: btc_data.head() -124/12: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() - -btc_data = btc_data.dropna() -ada_data ada_data.dropna() -124/13: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() - -btc_data = btc_data.dropna() -ada_data = ada_data.dropna() -124/14: btc_data.head() -124/15: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -124/16: -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/17: - -plt.plot(y_btc_test, label='Actual BTC') -plt.plot(btc_pred, label='Predicted BTC') -plt.legend() -plt.show() - -plt.plot(y_ada_test, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/18: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -124/19: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -124/20: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() - -btc_data = btc_data.dropna() -ada_data = ada_data.dropna() -124/21: btc_data.head() -124/22: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -124/23: -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/24: btc_pred -124/25: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -# X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -# X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -N = 365 -btc_test = btc_data.iloc[-N:] -btc_train = btc_data.iloc[:-N] - -ada_test = btc_data.iloc[-N:] -ada_train = btc_data.iloc[:-N] -124/26: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -# X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -# X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -N = 365 -x_btc_test = X_btc.iloc[-N:] -y_btc_test = y_btc.iloc[-N:] - -x_btc_train = X_btc.iloc[:-N] -y_btc_train = y_btc.iloc[:-N] - -x_ada_test = X_btc.iloc[-N:] -y_ada_test = y_btc.iloc[-N:] - -x_ada_train = X_btc.iloc[:-N] -y_ada_train = y_btc.iloc[:-N] -124/27: -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/28: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -124/29: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -124/30: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() - -btc_data = btc_data.dropna() -ada_data = ada_data.dropna() -124/31: btc_data.head() -124/32: -# Split the data into X (features) and y (target) -X_btc = btc_data[['SMA5', 'SMA20', 'SMA60']] -y_btc = btc_data['Close'] -X_ada = ada_data[['SMA5', 'SMA20', 'SMA60']] -y_ada = ada_data['Close'] - -# Split the data into training and testing sets -# X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -# X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -N = 365 -x_btc_test = X_btc.iloc[-N:] -y_btc_test = y_btc.iloc[-N:] - -x_btc_train = X_btc.iloc[:-N] -y_btc_train = y_btc.iloc[:-N] - -x_ada_test = X_btc.iloc[-N:] -y_ada_test = y_btc.iloc[-N:] - -x_ada_train = X_btc.iloc[:-N] -y_ada_train = y_btc.iloc[:-N] -124/33: -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/34: -# Split the data into X (features) and y (target) -X_btc_train = btc_train[['SMA5', 'SMA20', 'SMA60']] -y_btc_train = btc_train['Close'] -X_btc_test = btc_test[['SMA5', 'SMA20', 'SMA60']] -y_btc_test = btc_test['Close'] - -X_ada_train = ada_train[['SMA5', 'SMA20', 'SMA60']] -y_ada_train = ada_train['Close'] -X_ada_test = ada_test[['SMA5', 'SMA20', 'SMA60']] -y_ada_test = ada_test['Close'] - -# Split the data into training and testing sets -# X_btc_train, X_btc_test, y_btc_train, y_btc_test = train_test_split(X_btc, y_btc, test_size=0.2, shuffle=False) -# X_ada_train, X_ada_test, y_ada_train, y_ada_test = train_test_split(X_ada, y_ada, test_size=0.2, shuffle=False) -124/35: -# Create and fit the linear regression model for BTC -model_btc = LinearRegression() -model_btc.fit(X_btc_train, y_btc_train) - -# Create and fit the linear regression model for ADA -model_ada = LinearRegression() -model_ada.fit(X_ada_train, y_ada_train) - -# Make predictions on the testing data -btc_pred = model_btc.predict(X_btc_test) -ada_pred = model_ada.predict(X_ada_test) -124/36: - -plt.plot(y_btc_test, label='Actual BTC') -plt.plot(btc_pred, label='Predicted BTC') -plt.legend() -plt.show() - -plt.plot(y_ada_test, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/37: - -plt.plot(y_btc_train, label='Actual BTC') -plt.plot(btc_pred, label='Predicted BTC') -plt.legend() -plt.show() - -plt.plot(y_ada_train, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/38: -plt.plot(y_btc_test, label='Actual BTC') -plt.plot(btc_pred, label='Predicted BTC') -plt.legend() -plt.show() - -plt.plot(y_ada_train, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/39: -plt.plot(X_train, y_train, 'b.', label='Training Data') -plt.plot(X_test, y_test, 'r.', label='Test Data') -plt.plot(X_test, y_pred, 'g.', label='Predictions') -plt.legend() -plt.show() - -plt.plot(y_ada_train, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/40: -plt.plot(X_btc_train, y_btc_train, 'b.', label='Training Data') -plt.plot(X_btc_test, y_btc_test, 'r.', label='Test Data') -plt.plot(X_btc_test, btc_pred, 'g.', label='Predictions') -plt.legend() -plt.show() - -plt.plot(y_ada_train, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -124/41: plt.plot(btc_data, 'b.', label='Training Data') -124/42: plt.plot(btc_data, label='Training Data') -124/43: -plt.plot(btc_data, label='Training Data') -plt.show() -124/44: -plt.plot(btc_data, label='Training Data') -plt.plot(btc_pred, label='Training Data') - -plt.show() -124/45: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -# Load data -# data = pd.read_csv("your_data.csv", index_col="Date", parse_dates=True) - -# Split data into train and test -train_data = btc_data.iloc[:len(data) - 10] -test_data = btc_data.iloc[len(data) - 10:] - -# Fit ARIMA model -model = ARIMA(train_data, order=(1, 1, 1)) -model_fit = model.fit() - -# Make predictions -start_index = len(train_data) -end_index = len(train_data) + len(test_data) - 1 -predictions = model_fit.predict(start=start_index, end=end_index) - -# Calculate RMSE -rmse = np.sqrt(mean_squared_error(test_data, predictions)) - -# Plot data -plt.plot(train_data, label="Training Data") -plt.plot(test_data, label="Test Data") -plt.plot(predictions, label="Predictions", color="red") -plt.legend() -plt.title("Time Series Prediction with ARIMA") -plt.xlabel("Date") -plt.ylabel("Value") -plt.show() - -print("RMSE:", rmse) -124/46: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -# Load data -# data = pd.read_csv("your_data.csv", index_col="Date", parse_dates=True) - -# Split data into train and test -train_data = btc_data.iloc[:len(data) - 10] -test_data = btc_data.iloc[len(data) - 10:] - -# Fit ARIMA model -model = ARIMA(train_data, order=(1, 1, 1)) -model_fit = model.fit() - -# Make predictions -start_index = len(train_data) -end_index = len(train_data) + len(test_data) - 1 -predictions = model_fit.predict(start=start_index, end=end_index) - -# Calculate RMSE -rmse = np.sqrt(mean_squared_error(test_data, predictions)) - -# Plot data -plt.plot(train_data, label="Training Data") -plt.plot(test_data, label="Test Data") -plt.plot(predictions, label="Predictions", color="red") -plt.legend() -plt.title("Time Series Prediction with ARIMA") -plt.xlabel("Date") -plt.ylabel("Value") -plt.show() - -print("RMSE:", rmse) -124/47: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -# Load data -# data = pd.read_csv("your_data.csv", index_col="Date", parse_dates=True) - -# Split data into train and test -train_data = btc_data.iloc[:len(btc_data) - 10] -test_data = btc_data.iloc[len(btc_data) - 10:] - -# Fit ARIMA model -model = ARIMA(train_data, order=(1, 1, 1)) -model_fit = model.fit() - -# Make predictions -start_index = len(train_data) -end_index = len(train_data) + len(test_data) - 1 -predictions = model_fit.predict(start=start_index, end=end_index) - -# Calculate RMSE -rmse = np.sqrt(mean_squared_error(test_data, predictions)) - -# Plot data -plt.plot(train_data, label="Training Data") -plt.plot(test_data, label="Test Data") -plt.plot(predictions, label="Predictions", color="red") -plt.legend() -plt.title("Time Series Prediction with ARIMA") -plt.xlabel("Date") -plt.ylabel("Value") -plt.show() - -print("RMSE:", rmse) -124/48: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima.model import ARIMA -from sklearn.metrics import mean_squared_error - -# Load data -# data = pd.read_csv("your_data.csv", index_col="Date", parse_dates=True) - -# Split data into train and test -train_data = btc_data.iloc[:len(btc_data) - 10] -test_data = btc_data.iloc[len(btc_data) - 10:] - -# Fit ARIMA model -model = ARIMA(train_data, order=(1, 1, 1)) -model_fit = model.fit() - -# Make predictions -start_index = len(train_data) -end_index = len(train_data) + len(test_data) - 1 -predictions = model_fit.predict(start=start_index, end=end_index) - -# Calculate RMSE -rmse = np.sqrt(mean_squared_error(test_data, predictions)) - -# Plot data -plt.plot(train_data, label="Training Data") -plt.plot(test_data, label="Test Data") -plt.plot(predictions, label="Predictions", color="red") -plt.legend() -plt.title("Time Series Prediction with ARIMA") -plt.xlabel("Date") -plt.ylabel("Value") -plt.show() - -print("RMSE:", rmse) -124/49: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data() - self.train_data, self.test_data = self.split_data() - - # Load data from a CSV file - def load_data(self, file_path): - data = pd.read_csv(file_path) - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def load_data(self): - # Load data from the Coinbase API - pass # Replace with your own code to load data from the Coinbase API - - def split_data(self): - # Split the data into train and test sets - pass # Replace with your own code to split the data - - def plot_data(self, predictions): - # Plot the training data, test data, and predictions - pass # Replace with your own code to plot the data - - def predict(self): - # Fit an ARIMA model and make predictions - model = ARIMA(self.train_data, order=(1, 1, 1)) - model_fit = model.fit() - start_index = len(self.train_data) - end_index = len(self.train_data) + len(self.test_data) - 1 - predictions = model_fit.predict(start=start_index, end=end_index) - - # Calculate RMSE - rmse = np.sqrt(mean_squared_error(self.test_data, predictions)) - - # Plot the data and predictions - self.plot_data(predictions) - - return predictions, rmse - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/50: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data() - self.train_data, self.test_data = self.split_data() - - # Load data from a CSV file - def load_data(self, file_path): - data = pd.read_csv(file_path) - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - # Fit an ARIMA model and make predictions - model = ARIMA(self.train_data, order=(1, 1, 1)) - model_fit = model.fit() - start_index = len(self.train_data) - end_index = len(self.train_data) + len(self.test_data) - 1 - predictions = model_fit.predict(start=start_index, end=end_index) - - # Calculate RMSE - rmse = np.sqrt(mean_squared_error(self.test_data, predictions)) - - # Plot the data and predictions - self.plot_data(predictions) - - return predictions, rmse - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/51: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data() - self.train_data, self.test_data = self.split_data() - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - # Fit an ARIMA model and make predictions - model = ARIMA(self.train_data, order=(1, 1, 1)) - model_fit = model.fit() - start_index = len(self.train_data) - end_index = len(self.train_data) + len(self.test_data) - 1 - predictions = model_fit.predict(start=start_index, end=end_index) - - # Calculate RMSE - rmse = np.sqrt(mean_squared_error(self.test_data, predictions)) - - # Plot the data and predictions - self.plot_data(predictions) - - return predictions, rmse - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/52: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data() - self.train_data, self.test_data = self.split_data() - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - # Fit an ARIMA model and make predictions - model = ARIMA(self.train_data, order=(1, 1, 1)) - model_fit = model.fit() - start_index = len(self.train_data) - end_index = len(self.train_data) + len(self.test_data) - 1 - predictions = model_fit.predict(start=start_index, end=end_index) - - # Calculate RMSE - rmse = np.sqrt(mean_squared_error(self.test_data, predictions)) - - # Plot the data and predictions - self.plot_data(predictions) - - return predictions, rmse - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - data = cp.load_data(file_path) - train_data, test_data = cp.split_data(data) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/53: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data(self.symbol) - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - # Fit an ARIMA model and make predictions - model = ARIMA(self.train_data, order=(1, 1, 1)) - model_fit = model.fit() - start_index = len(self.train_data) - end_index = len(self.train_data) + len(self.test_data) - 1 - predictions = model_fit.predict(start=start_index, end=end_index) - - # Calculate RMSE - rmse = np.sqrt(mean_squared_error(self.test_data, predictions)) - - # Plot the data and predictions - self.plot_data(predictions) - - return predictions, rmse - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/54: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data(self.symbol) - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train['Close'] - X_test = self.test[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/55: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - self.data = self.load_data(self.symbol) - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/56: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - data = self.add_features() - self.train_data, self.test_data = self.split_data(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/57: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - data = self.add_features(data) - self.train_data, self.test_data = self.split_data(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/58: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions, rmse = cp.predict() - print(f"RMSE: {rmse}") -124/59: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - plt.plot(self.data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() -124/60: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - # plt.plot(self.data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() -124/61: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - # plt.plot(self.data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() -124/62: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - # plt.plot(self.data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data" -124/63: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, data, title="Data"): - plt.plot(data) - # plt.plot(self.data) - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - # Plot the data and predictions - self.plot_data(predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/64: data -124/65: predictions -124/66: -s = data['close'] -s -124/67: -s = data.filter('close') -s -124/68: -s = data.filter('Close') -s -124/69: -s = data.filter('Close') -data.columns -124/70: -s = data.filter('Close') -s -124/71: -s = data.filter(['Close']) -s -124/72: -s = data.filter(['Close']) -s.append(predictions) -124/73: -s = data.filter(['Close']) -s.concat(predictions) -124/74: -s = data.filter(['Close']) -pd.concat([s, predictions]) -124/75: -s = data.filter(['Close']) -pd.concat([s, pd.DataFrame(predictions, columns['Close']) -124/76: -s = data.filter(['Close']) -pd.concat([s, pd.DataFrame(predictions, columns['Close'])) -124/77: -s = data.filter(['Close']) -pd.concat([s, pd.DataFrame(predictions, columns['Close']]) -124/78: -s = data.filter(['Close']) -pd.concat([s, pd.DataFrame(predictions, columns['Close'])]) -124/79: -s = data.filter(['Close']) -pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -124/80: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t.reset_index() -plt.plot(t) -plt.plot(data) -plt.show() -124/81: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/82: t -124/83: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/84: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -plt.plot(data) -plt.show() -124/85: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/86: t -124/87: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -#plt.plot(t) -#plt.plot(data) -plt.show() -124/88: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/89: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, actual, predictions=None, title="Data"): - plt.figure(figsize=(10, 6)) - plt.plot(actual, label='Actual Data') - if predictions is not None: - plt.plot(predictions, color='red', label='Predictions') - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit an ARIMA model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # Plot the data and predictions - self.plot_data(self.test_data['Close'], predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/90: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - plt.figure(figsize=(10, 6)) - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/91: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - plt.figure(figsize=(10, 6)) - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Calculating and plotting the error - error = test_data['Close'] - predictions - plt.plot(test_data.index, error, color='green', label='Prediction Error') - - - plt.title(title) - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/92: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = test_data['Close'] - predictions - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/93: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -from sklearn.metrics import mean_squared_error -124/94: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/95: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/96: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/97: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/98: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full['Close'], label='Actual Data', color='blue') - - ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/99: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full['Close'], label='Actual Data', color='blue') - - ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/100: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.6): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full['Close'], label='Actual Data', color='blue') - - ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/101: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full['Close'], label='Actual Data', color='blue') - - ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/102: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/103: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/104: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/105: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/106: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.4): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/107: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/108: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'] - predictions) - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/109: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'] - predictions) - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions, mse) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/110: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'] - predictions) - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/111: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'], predictions) - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/112: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'], predictions) - print(error - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/113: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - error = mean_squared_error(test_data['Close'], predictions) - print(error) - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/114: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/115: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - # mse = mean_squared_error(y_test, predictions) - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/116: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE' - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/117: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/118: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Assuming the model and test data are already available - last_data = self.data.iloc[-1] - future_dates = pd.date_range(start=last_data.name, periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - - # Here, you need to calculate SMA5, SMA20, SMA60 for the future dates. - # This is a simplified approach and might not be accurate. - # A more complex approach would involve using the model's predictions - # as part of the input for the next prediction. - for sma_period in [5, 20, 60]: - sma = self.data['Close'].rolling(sma_period).mean().iloc[-sma_period:] - extrapolated_sma = sma.append(future_df['Close']).fillna(method='ffill').rolling(sma_period).mean() - future_df[f'SMA{sma_period}'] = extrapolated_sma - - # Predict for future dates - future_predictions = self.model.predict(future_df[['SMA5', 'SMA20', 'SMA60']]) - - return future_predictions - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/119: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - future_data.loc[future_date, f'SMA{sma_period}'] = \ - future_data['Close'].rolling(sma_period).mean().iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/120: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - future_data.loc[future_date, f'SMA{sma_period}'] = \ - future_data['Close'].rolling(sma_period).mean().iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/121: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - future_data.loc[future_date, f'SMA{sma_period}'] = \ - future_data['Close'].rolling(sma_period).mean().iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - print(X_future, 'ai') - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/122: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - future_data.loc[future_date, f'SMA{sma_period}'] = \ - future_data['Close'].rolling(sma_period).mean().iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - print(future_data, 'ai') - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/123: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-120:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - future_data.loc[future_date, f'SMA{sma_period}'] = \ - future_data['Close'].rolling(sma_period).mean().iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - print(future_data, 'ai') - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/124: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/125: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/126: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/127: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/128: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - print(last_known_data) - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/129: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/130: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/131: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/132: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values, sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/133: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.dropna(), sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/134: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1].dropna() - # print(sma_values.dropna(), sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/135: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.dropna() - # print(sma_values.dropna(), sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/136: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/137: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1][-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/138: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/139: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], sma_period, 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/140: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60, 65]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], sma_period, 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/141: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60, 65, 120]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], sma_period, 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/142: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - # print(future_data) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60, 65, 99999]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1], sma_period, 'nan') - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/143: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[-historical_data_length:].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 30 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/144: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[-historical_data_length:].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/145: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[-historical_data_length:].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # # Ensure there are no NaN values in the input features - # if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - # continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/146: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[-historical_data_length:].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # # Ensure there are no NaN values in the input features - # if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - # continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/147: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # # Ensure there are no NaN values in the input features - # if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - # continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/148: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # # Ensure there are no NaN values in the input features - # if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - # continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/149: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/150: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -#plt.plot(t) -#plt.plot(data) -plt.show() -124/151: t -124/152: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.1): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/153: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/154: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/155: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -#plt.plot(t) -#plt.plot(data) -plt.show() -124/156: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -#plt.plot(t) -#plt.plot(data) -plt.show() -124/157: -s = data.filter(['Close']) -t = pd.concat([s, pd.DataFrame(predictions, columns=['Close'])]) -t = t.reset_index() -plt.plot(t) -#plt.plot(data) -plt.show() -124/158: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(test_data.index,full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/159: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [5, 20, 60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/160: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/161: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - # print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/162: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Ensure there's enough historical data for SMA calculations - historical_data_length = max(60, N) # At least as long as the longest SMA period - last_known_data = self.data.iloc[:-historical_data_length].copy() - - # Prepare DataFrame for future predictions - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each future day - for future_date in future_df.index: - # Update SMAs with available 'Close' data - for sma_period in [60]: - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - # print(sma_values) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Ensure there are no NaN values in the input features - if future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].isna().any(): - continue - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict and update 'Close' value - future_prediction = self.model.predict(X_future)[0] - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/163: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/164: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -124/165: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/1: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -from sklearn.metrics import mean_squared_error -129/2: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -129/3: -btc_data['SMA5'] = btc_data['Close'].rolling(5).mean() -btc_data['SMA20'] = btc_data['Close'].rolling(20).mean() -btc_data['SMA60'] = btc_data['Close'].rolling(60).mean() - -ada_data['SMA5'] = ada_data['Close'].rolling(5).mean() -ada_data['SMA20'] = ada_data['Close'].rolling(20).mean() -ada_data['SMA60'] = ada_data['Close'].rolling(60).mean() - -btc_data = btc_data.dropna() -ada_data = ada_data.dropna() - -# Create a new DataFrame with the last N rows for the testing set -btc_test = btc_data.iloc[-N:] -ada_test = ada_data.iloc[-N:] - -# Create a new DataFrame with all rows except the last N rows for the training set -btc_train = btc_data.iloc[:-N] -ada_train = ada_data.iloc[:-N] -129/4: -plt.plot(X_btc_train, y_btc_train, 'b.', label='Training Data') -plt.plot(X_btc_test, y_btc_test, 'r.', label='Test Data') -plt.plot(X_btc_test, btc_pred, 'g.', label='Predictions') -plt.legend() -plt.show() - -plt.plot(y_ada_train, label='Actual ADA') -plt.plot(ada_pred, label='Predicted ADA') -plt.legend() -plt.show() -129/5: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/6: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Calculate Mean Squared Error - mse = mean_squared_error(y_test, predictions) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions, mse) - - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/7: t -129/8: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, mse, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/9: cp.forecast() -129/10: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/11: cp.forecast() -129/12: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period, min_periods=1).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/13: cp.forecast() -129/14: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/15: cp.forecast() -129/16: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1]) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/17: cp.forecast() -129/18: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for future_date in future_df.index: - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1]) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/19: cp.forecast() -129/20: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1]) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/21: cp.forecast() -129/22: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data #.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/23: cp.forecast() -129/24: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/25: cp.forecast() -129/26: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/27: -future_predictions = cp.predict_future(window=30) -print(future_predictions) -129/28: -import pandas as pd -import yfinance as yf -from sklearn.linear_model import LinearRegression -from sklearn.model_selection import train_test_split -import matplotlib.pyplot as plt -from sklearn.metrics import mean_squared_error -from datetime import datetime, timedelta -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -129/29: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -129/30: - - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/31: -future_predictions = cp.predict_future(window=30) -print(future_predictions) -129/32: -import pandas as pd -import yfinance as yf -import numpy as np -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -129/33: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -129/34: - - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data - - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions= cp.predict() - data = cp.data -129/35: -future_predictions = cp.predict_future(window=30) -print(future_predictions) -129/36: - - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - - # ax1.plot(test_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # # Adding legends and title - # ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_future(self, N): - # Initialize the future DataFrame with the latest actual data - last_known_data = self.data.iloc[-60:].copy() # using 60 days to ensure SMA60 can be calculated - future_dates = pd.date_range(start=last_known_data.index[-1], periods=N+1, closed='right') - future_df = pd.DataFrame(index=future_dates, columns=self.data.columns) - future_data = pd.concat([last_known_data, future_df]) - - # Iteratively predict each day and use that prediction for subsequent calculations - for index, future_date in future_df.iterrows(): - for sma_period in [5, 20, 60]: - # Calculate SMA values, using available 'Close' values - sma_values = future_data['Close'].rolling(sma_period).mean() - print(sma_values[-1], future_data['Close']) - future_data.loc[future_date, f'SMA{sma_period}'] = sma_values.iloc[-1] - print(sma_values.iloc[-1]) - - # Prepare the data for the model - X_future = future_data.loc[future_date, ['SMA5', 'SMA20', 'SMA60']].values.reshape(1, -1) - - # Predict - future_prediction = self.model.predict(X_future)[0] - - # Use the prediction as the 'Close' value for the next prediction - future_data.loc[future_date, 'Close'] = future_prediction - - return future_data.loc[future_df.index, 'Close'] - - def plot_data_with_future(self, full_data, test_data, predictions, future_predictions, title="Data"): - plt.figure(figsize=(12, 7)) - - # Plotting the actual data and predictions - plt.plot(full_data['Close'], label='Actual Data') - plt.plot(test_data.index, predictions, color='red', label='Predictions') - - # Plotting future predictions - future_dates = pd.date_range(start=test_data.index[-1], periods=len(future_predictions)+1, closed='right') - plt.plot(future_dates, future_predictions, color='orange', label='Future Predictions') - - plt.title(f"{title}\nMean Squared Error: {mse:.2f}") - plt.xlabel("Time") - plt.ylabel("Value") - plt.legend() - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def forecast(self): - N = 365 # number of days to predict into the future - future_predictions = self.predict_future(N) - - # Plot the full data, predictions, and future predictions - self.plot_data_with_future(self.data, self.test_data, predictions, future_predictions) - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data -129/37: -# Example usage -crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol -cp = CryptoPrediction(crypto_symbol) -predictions= cp.predict() -data = cp.data -129/38: -future_predictions = cp.predict_future(window=30) -print(future_predictions) -129/39: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 1)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/40: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/41: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array([x[-1]])) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/42: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array([x[-1]])) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/43: cp.predict_next_close -129/44: cp.predict_next_close() -129/45: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array([x[-1]])) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/46: cp.predict_next_close() -129/47: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array([x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/48: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/49: cp.predict_next_close() -129/50: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/51: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/52: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(test_data.index, label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/53: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/54: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/55: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - ax1.set_xlim(0, 2 * np.pi) - ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/56: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(0, 2 * np.pi) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/57: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - ax1.set_xlim(2023, :) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/58: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/59: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/60: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - # ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/61: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - # Create the sliders and button - ax_xlim = plt.axes([0.25, 0.05, 0.5, 0.03]) - ax_ylim = plt.axes([0.25, 0.01, 0.5, 0.03]) - slider_xlim = Slider(ax_xlim, 'xlim', 0, 2 * np.pi, valinit=ax.get_xlim()) - slider_ylim = Slider(ax_ylim, 'ylim', -1, 1, valinit=ax.get_ylim()) - reset_button = plt.axes([0.8, 0.025, 0.1, 0.04]) - button = plt.Button(reset_button, 'Reset', hovercolor='0.975') - - # Update the plot when the sliders are changed - def update(val): - ax.set_xlim(slider_xlim.val) - ax.set_ylim(slider_ylim.val) - fig.canvas.draw_idle() - - slider_xlim.on_changed(update) - slider_ylim.on_changed(update) - - # Reset the view limits when the button is clicked - def reset(event): - slider_xlim.reset() - slider_ylim.reset() - - button.on_clicked(reset) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/62: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - # Create the sliders and button - ax_xlim = plt.axes([0.25, 0.05, 0.5, 0.03]) - ax_ylim = plt.axes([0.25, 0.01, 0.5, 0.03]) - slider_xlim = Slider(ax_xlim, 'xlim', 0, 2 * np.pi, valinit=ax.get_xlim()) - slider_ylim = Slider(ax_ylim, 'ylim', -1, 1, valinit=ax.get_ylim()) - reset_button = plt.axes([0.8, 0.025, 0.1, 0.04]) - button = plt.Button(reset_button, 'Reset', hovercolor='0.975') - - # Update the plot when the sliders are changed - def update(val): - ax.set_xlim(slider_xlim.val) - ax.set_ylim(slider_ylim.val) - fig.canvas.draw_idle() - - slider_xlim.on_changed(update) - slider_ylim.on_changed(update) - - # Reset the view limits when the button is clicked - def reset(event): - slider_xlim.reset() - slider_ylim.reset() - - button.on_clicked(reset) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/63: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - # Create the sliders and button - ax_xlim = plt.axes([0.25, 0.05, 0.5, 0.03]) - ax_ylim = plt.axes([0.25, 0.01, 0.5, 0.03]) - slider_xlim = Slider(ax_xlim, 'xlim', 0, 2 * np.pi, valinit=ax.get_xlim()) - slider_ylim = Slider(ax_ylim, 'ylim', -1, 1, valinit=ax.get_ylim()) - reset_button = plt.axes([0.8, 0.025, 0.1, 0.04]) - button = plt.Button(reset_button, 'Reset', hovercolor='0.975') - - # Update the plot when the sliders are changed - def update(val): - ax1.set_xlim(slider_xlim.val) - ax.1set_ylim(slider_ylim.val) - fig.canvas.draw_idle() - - slider_xlim.on_changed(update) - slider_ylim.on_changed(update) - - # Reset the view limits when the button is clicked - def reset(event): - slider_xlim.reset() - slider_ylim.reset() - - button.on_clicked(reset) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/64: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - # Create the sliders and button - ax_xlim = plt.axes([0.25, 0.05, 0.5, 0.03]) - ax_ylim = plt.axes([0.25, 0.01, 0.5, 0.03]) - slider_xlim = Slider(ax_xlim, 'xlim', 0, 2 * np.pi, valinit=ax.get_xlim()) - slider_ylim = Slider(ax_ylim, 'ylim', -1, 1, valinit=ax.get_ylim()) - reset_button = plt.axes([0.8, 0.025, 0.1, 0.04]) - button = plt.Button(reset_button, 'Reset', hovercolor='0.975') - - # Update the plot when the sliders are changed - def update(val): - ax1.set_xlim(slider_xlim.val) - ax1.set_ylim(slider_ylim.val) - fig.canvas.draw_idle() - - slider_xlim.on_changed(update) - slider_ylim.on_changed(update) - - # Reset the view limits when the button is clicked - def reset(event): - slider_xlim.reset() - slider_ylim.reset() - - button.on_clicked(reset) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/65: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - # Create the sliders and button - ax_xlim = plt.axes([0.25, 0.05, 0.5, 0.03]) - ax_ylim = plt.axes([0.25, 0.01, 0.5, 0.03]) - slider_xlim = Slider(ax_xlim, 'xlim', 0, 2 * np.pi, valinit=ax1.get_xlim()) - slider_ylim = Slider(ax_ylim, 'ylim', -1, 1, valinit=ax1.get_ylim()) - reset_button = plt.axes([0.8, 0.025, 0.1, 0.04]) - button = plt.Button(reset_button, 'Reset', hovercolor='0.975') - - # Update the plot when the sliders are changed - def update(val): - ax1.set_xlim(slider_xlim.val) - ax1.set_ylim(slider_ylim.val) - fig.canvas.draw_idle() - - slider_xlim.on_changed(update) - slider_ylim.on_changed(update) - - # Reset the view limits when the button is clicked - def reset(event): - slider_xlim.reset() - slider_ylim.reset() - - button.on_clicked(reset) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/66: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/67: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.2): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/68: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.2): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/69: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.2): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/70: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/71: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/72: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - self.train_data, self.test_data = self.split_data(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - return data.dropna() - - # Split data into training and test sets - def split_data(self, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - return train_data, test_data - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train = self.train_data[['SMA5', 'SMA20', 'SMA60']] - y_train = self.train_data['Close'] - X_test = self.test_data[['SMA5', 'SMA20', 'SMA60']] - y_test = self.test_data['Close'] - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/73: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data(self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/74: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/75: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/76: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - print(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETH-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/77: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - print(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/78: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - print(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - print(data) - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/79: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - print(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - print(data) - return data.dropna(inplace=True) - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/80: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - print(self.data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - print(data) - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/81: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - future_predictions = cp.predict_future(window=30) - print(future_predictions) -129/82: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ETC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/83: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-01-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/84: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/85: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[target]) - y_train = train_data.Close_Tomorrow - - X_test = test_data.drop(columns=[target]) - y_test = test_data.Close_Tomorrow - - return X_train, y_train, X_test, y_test - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/86: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(window=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/87: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/88: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/89: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/90: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/91: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/92: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2020-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', linestyle='-', alpha=0.7) - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.7) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/93: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', linestyle='-', alpha=0.7) - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.7) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/94: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', linestyle='-', alpha=0.7) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.7) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/95: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.7) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/96: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.7) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/97: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.4) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/98: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-07') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/99: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2022-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/100: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/101: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/102: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2022-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/103: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/104: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=10): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/105: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/106: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/107: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data, window_size=10): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/108: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/109: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/110: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -129/111: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/1: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/2: -import pandas as pd -import yfinance as yf -import numpy as np -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -132/3: -def download_data(ticker, start_date, end_date): - data = yf.download(ticker, start=start_date, end=end_date, progress=False) - data.drop(['Adj Close'], axis=1, inplace=True) - return data - -btc_data = download_data('BTC-USD', '2018-01-01', '2023-12-07') -ada_data = download_data('ADA-USD', '2018-01-01', '2023-12-07') -132/4: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/5: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.data = self.add_features(data) - self.window_size = window_size - print(self.window_size) - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/6: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/7: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(window_size): - plt.figure(figsize=(12, 6)) - plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices for the specific range - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/8: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/9: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5, window_size=30): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - print(train_data.columns, window_size) - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data, window_size=window_size) - models = [] - for i in range(window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/10: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/11: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/12: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 100 # Replace with your desired starting index - end_index = 200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/13: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -300 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/14: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -00 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/15: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -10 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/16: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -50 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/17: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -50 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/18: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.5): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -50 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/19: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -50 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/20: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -20 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/21: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -50 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/22: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 0 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/23: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/24: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - #if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/25: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/26: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'] #.iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/27: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'] #.iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index #[start_index:end_index], - y_preds[i] #[start_index:end_index], - label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/28: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index #[start_index:end_index], - y_test[f'Close_{i+1}'] #.iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index #[start_index:end_index], - y_preds[i] #[start_index:end_index], - label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/29: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[:] #[start_index:end_index], - y_test[f'Close_{i+1}'] #.iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index #[start_index:end_index], - y_preds[i] #[start_index:end_index], - label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/30: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[0:] #[start_index:end_index], - y_test[f'Close_{i+1}'] #.iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index #[start_index:end_index], - y_preds[i] #[start_index:end_index], - label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/31: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -500 # Replace with your desired starting index - end_index = -200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/32: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -1500 # Replace with your desired starting index - end_index = -1200 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/33: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -120 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/34: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/35: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/36: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/37: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/38: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/39: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/40: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/41: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - for i in range(window_size): - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - break - - # Plot the corresponding predictions - for i in range(window_size): - plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - - # Visualize the predictions - # for i in range(window_size): - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - # plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - # plt.show() - - # # Create a single plot to visualize all predictions and the true closing prices - # plt.figure(figsize=(12, 6)) - # plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # # Plot the true closing prices - # # for i in range(window_size): - # # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # # break - - # # # Plot the corresponding predictions - # # for i in range(window_size): - # # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - # start_index = -150 # Replace with your desired starting index - # end_index = -140 # Replace with your desired ending index - - # # Create separate plots for the true closing prices and predictions for each day in the window - # for i in range(self.window_size): - # # Plot the true closing prices for the specific range - # if i == 0: - # plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - # label='True', linestyle='-') - - # # Plot the corresponding predictions for the specific range - # plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - # plt.legend() - # plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/42: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/43: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows() - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/44: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -140 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/45: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -130 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/46: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/47: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/48: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_pred - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/49: predictions -132/50: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/51: predictions -132/52: -avg = np.mean(predictions) -avg -132/53: -avg = np.mean(predictions, axis=0) -avg -132/54: -avg = np.mean(predictions, axis=0) -plt.plot(avg) -132/55: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/56: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test['Close'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/57: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test['Close_0'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/58: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - predictions = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/59: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows(30) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/60: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = -150 # Replace with your desired starting index - end_index = -90 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows(120) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/61: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 0 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 30) - predictions = cp.predict_windows(120) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/62: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 0 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 120) - predictions = cp.predict_windows(120) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/63: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Plot the true closing prices - # for i in range(window_size): - # plt.plot(y_test.index, y_test[f'Close_{i+1}'], label=f'Day {i+1} True', alpha=1) - # break - - # # Plot the corresponding predictions - # for i in range(window_size): - # plt.plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 0 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - # plt.figure(figsize=(12, 6)) - # plt.title(f'Day {i+1} - True vs. Predicted Closing Prices') - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - # plt.grid(True) - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return y_preds - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 60) - predictions = cp.predict_windows(60) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/64: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - plot(y_test.index, y_preds[i], label=f'Day {i+1} Predicted', linestyle='--', alpha=0.6) - start_index = 0 # Replace with your desired starting index - end_index = -1 # Replace with your desired ending index - - # Create separate plots for the true closing prices and predictions for each day in the window - for i in range(self.window_size): - - # Plot the true closing prices for the specific range - if i == 0: - plt.plot(y_test.index[start_index:end_index], y_test[f'Close_{i+1}'].iloc[start_index:end_index], - label='True', linestyle='-') - - # Plot the corresponding predictions for the specific range - plt.plot(y_test.index[start_index:end_index], y_preds[i][start_index:end_index], label='Predicted', linestyle='--') - - - plt.legend() - plt.show() - return models - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 60) - models = cp.predict_windows(60) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/65: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - days_ahead = 10 # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 60) - models = cp.predict_windows(60) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/66: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 60) - models = cp.predict_windows(60) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/67: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - # if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 60) - models = cp.predict_windows(60) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/68: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/69: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/70: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index[:-window_size, avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/71: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'], label='Actual') - plt.plot(y_test.index[:-window_size], avg_pred, label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/72: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][window_size:], label='Actual') - plt.plot(y_test.index[:-window_size], avg_pred[:-window_size], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/73: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][window_size:], label='Actual') - plt.plot(y_test.index[window_size:}], avg_pred[:-window_size], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/75: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][window_size:], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[:-window_size], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/76: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index, y_test[f'Close_{i+1}'], label='Actual') - plt.plot(y_test.index, y_preds[i], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/77: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+1}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], y_preds[i][window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - predictions_for_days_ahead = [] - - for i in range(self.window_size): - days_ahead = i - # Plot the true closing prices for the specific day in the future - if i == 0: - plt.plot( - y_test.index[days_ahead:], - y_test[f'Close_{i+1}'].iloc[days_ahead:], - label=f'True Day {i+1}', - linestyle='-' - ) - - # Plot the corresponding predictions for the specific day in the future - plt.plot( - y_test.index[days_ahead:], - y_preds[i][days_ahead:], - label=f'Predicted Day {i+1}', - linestyle='--' - ) - - # Append the prediction for the specified day ahead to the list - predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/78: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+1}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], y_preds[i][window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - # predictions_for_days_ahead = [] - - # for i in range(self.window_size): - # days_ahead = i - # # Plot the true closing prices for the specific day in the future - # # if i == 0: - # plt.plot( - # y_test.index[days_ahead:], - # y_test[f'Close_{i+1}'].iloc[days_ahead:], - # label=f'True Day {i+1}', - # linestyle='-' - # ) - - # # Plot the corresponding predictions for the specific day in the future - # plt.plot( - # y_test.index[days_ahead:], - # y_preds[i][days_ahead:], - # label=f'Predicted Day {i+1}', - # linestyle='--' - # ) - - # # Append the prediction for the specified day ahead to the list - # predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 10) - models = cp.predict_windows(10) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/79: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+1}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], y_preds[i][window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Create a single plot to visualize all predictions and the true closing prices - plt.figure(figsize=(12, 6)) - plt.title('Predicted vs. True Closing Prices for Each Day in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - # Specify the number of days ahead to predict - # days_ahead = self.window_size # Change this to your desired number of days - - # Create a list to store the predictions for each day ahead - # predictions_for_days_ahead = [] - - # for i in range(self.window_size): - # days_ahead = i - # # Plot the true closing prices for the specific day in the future - # # if i == 0: - # plt.plot( - # y_test.index[days_ahead:], - # y_test[f'Close_{i+1}'].iloc[days_ahead:], - # label=f'True Day {i+1}', - # linestyle='-' - # ) - - # # Plot the corresponding predictions for the specific day in the future - # plt.plot( - # y_test.index[days_ahead:], - # y_preds[i][days_ahead:], - # label=f'Predicted Day {i+1}', - # linestyle='--' - # ) - - # # Append the prediction for the specified day ahead to the list - # predictions_for_days_ahead.append(y_preds[i][days_ahead]) - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 4) - models = cp.predict_windows(4) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/80: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 4) - models = cp.predict_windows(4) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/81: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - cp = CryptoPrediction(crypto_symbol, 4) - models = cp.predict_windows(4) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/82: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "BTC-USD" # Replace with your desired cryptocurrency symbol - window = 60 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/83: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 60 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) -132/84: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 60 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 10 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/85: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 10 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 10 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/86: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 2 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 20 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/87: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 2 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 10 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/88: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 20 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 20 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/89: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 20 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 20 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/90: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-05-01', '2023-12-08') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 40 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/91: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 40 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/92: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - - def forecast_window(self, window_size=30, forecast_steps=10): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - - # Create a list to store the forecasts for each day ahead - forecasts = [] - - for i in range(forecast_steps): - future_features = X_test.iloc[i:i+1] # Take one day's worth of features - day_ahead_predictions = [] - - for model in models: - y_pred = model.predict(future_features) - day_ahead_predictions.append(y_pred[0]) - - # Append the predictions for the day ahead to the list of forecasts - forecasts.append(day_ahead_predictions) - - # Update the features for the next day by shifting them forward - future_features = future_features.shift(-1) - future_features['SMA5'] = future_features['SMA5'].fillna(future_features['SMA5'].iloc[-1]) - future_features['SMA20'] = future_features['SMA20'].fillna(future_features['SMA20'].iloc[-1]) - future_features['SMA60'] = future_features['SMA60'].fillna(future_features['SMA60'].iloc[-1]) - - # Create a DataFrame to store the forecasts - forecast_df = pd.DataFrame(forecasts, columns=[f'Day_{i+1}' for i in range(forecast_steps)], index=y_test.index[:forecast_steps]) - - # Plot the forecasts - plt.figure(figsize=(12, 6)) - plt.title('Forecasts for Closing Prices in the Window') - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - - for i in range(forecast_steps): - plt.plot(forecast_df.index, forecast_df[f'Day_{i+1}'], label=f'Day {i+1} Forecast', linestyle='--') - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Return the forecasts DataFrame - return forecast_df - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data - - # future_predictions = cp.predict_future(window=30) - # print(future_predictions) - forecast_steps = 40 # Specify the number of forecast steps - forecasts = cp.forecast_window(60, forecast_steps) - print(forecasts) -132/93: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict_next_close(self, window=30): - # Create the X and y data - x = self.data.Close.values[:-1] - y = self.data.Close.values[1:] - - # Split the data into train and test sets - x_train, x_test = x[:-window], x[-window:] - y_train, y_test = y[:-window], y[-window:] - - # Create and fit the Linear Regression model - lr = LinearRegression() - lr.fit(x_train.reshape(-1, 1), y_train) - - # Predict the next close value - next_close_pred = lr.predict(np.array(x)) - - return next_close_pred - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - - def predict_future(self, window=10): - start_date = self.test_data.index[-1] + timedelta(days=1) - end_date = start_date + timedelta(days=window-1) - future_dates = pd.date_range(start_date, end_date, freq='D') - - scaler = StandardScaler() - scaled_features = scaler.fit_transform(self.test_data[['SMA5', 'SMA20', 'SMA60']]) - scaled_features_df = pd.DataFrame(scaled_features, columns=['SMA5', 'SMA20', 'SMA60'], index=self.test_data.index) - - future_features = scaled_features_df.tail(window).values - future_predictions = self.model.predict(future_features) - future_predictions = scaler.inverse_transform(future_predictions.reshape(-1, 3)) - - predicted_data = pd.DataFrame({'Date': future_dates, 'Close': future_predictions.ravel()}, - index=future_dates) - predicted_data['SMA5'] = predicted_data['Close'].rolling(5).mean() - predicted_data['SMA20'] = predicted_data['Close'].rolling(20).mean() - predicted_data['SMA60'] = predicted_data['Close'].rolling(60).mean() - return predicted_data - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.data -132/94: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict()" -132/95: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict() -132/96: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2018-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict() -132/97: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - print(self.data) - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict() -132/98: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict() -132/99: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - # models = cp.predict_windows(window) - data = cp.predict() -132/100: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/101: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/102: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 40 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/103: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - # if i == 0: - # i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/104: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - plt.figure(figsize=(10, 5)) - plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/105: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - for i in range(window_size): - if i == 0: - i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/106: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/107: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=1 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/108: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=1 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - ax2 = ax1.twinx() - error = (test_data['Close_Tomorrow'] - predictions) / 100 - ax2.plot(test_data.index, error, color='green', label='Prediction Error') - ax2.set_ylabel('Error', color='green') - ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/109: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/110: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/111: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_0'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/112: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+1}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/113: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/114: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual')/ - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/115: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/116: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/117: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(1, self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+0}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/118: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/119: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - # data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/120: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - # data['Close_0'] = data['Close'] - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=0 - plt.plot(y_test.index[i:], y_test[f'Close_{i+0}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/121: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=1 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - # if i == 0: - # i = 1 - # plt.figure(figsize=(10, 5)) - # plt.title(f"Day {i+1} Prediction") - - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # plt.legend() - # plt.xlabel('Date') - # plt.ylabel('Closing Price') - #plt.grid(True) - #plt.show() - - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close_T'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/122: from utilsforecast.plotting import plot_series -132/123: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - - - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=1 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - # ax1.set_xlim(2023, 2024) - # ax1.set_ylim(-1, 1) - - # Creating a secondary y-axis for the error plot - # ax2 = ax1.twinx() - # error = (test_data['Close_T'] - predictions) / 100 - # ax2.plot(test_data.index, error, color='green', label='Prediction Error') - # ax2.set_ylabel('Error', color='green') - # ax2.tick_params(axis='y', labelcolor='green') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - data = cp.predict() -132/124: -data = cp.data -data -132/125: -data = cp.data -data['unique_id' = crypto_symbol -data['df'] = data.index.values -132/126: -data = cp.data -data['unique_id'] = crypto_symbol -data['df'] = data.index.values -132/127: -data = cp.data -data['unique_id'] = crypto_symbol -data['df'] = data.index.values -132/128: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -132/129: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data -132/130: -fig = plot_series(data) -fig -132/131: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data['y'] = data['Close'] -132/132: -fig = plot_series(data) -fig -132/133: -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from statsmodels.tsa.arima_model import ARIMA -from sklearn.metrics import mean_squared_error -from sklearn.linear_model import LinearRegression -from sklearn.preprocessing import StandardScaler -from datetime import datetime, timedelta -from matplotlib.widgets import Slider - -class CryptoPrediction: - def __init__(self, symbol, window_size=30): - self.symbol = symbol - data = self.load_data(self.symbol) - self.window_size = window_size - self.data = self.add_features(data) - self.save_data = pd.DataFrame() - self.save_data['Close'] = self.data['Close'] - - # Load data from a CSV file - def load_data(self, ticker='BTC-USD'): - data = download_data(ticker, '2023-01-01', '2023-12-09') - return data - - def add_features(self, data): - data['SMA5'] = data['Close'].rolling(5).mean() - data['SMA20'] = data['Close'].rolling(20).mean() - data['SMA60'] = data['Close'].rolling(60).mean() - data['Close_Tomorrow'] = data['Close'].shift(-1) - - for i in range(1, self.window_size + 1): - data[f'Close_{i}'] = data['Close'].shift(-i) - - return data.dropna() - - # Split data into training and test sets - def split_data(self, target, data, train_ratio=0.8): - train_size = int(len(data) * train_ratio) - train_data = data[:train_size] - test_data = data[train_size:] - - self.train_data = train_data - self.test_data = test_data - - X_train = train_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_train = train_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - X_test = test_data.drop(columns=[f'Close_{i}' for i in range(1, self.window_size + 1)]) # Features - y_test = test_data[[f'Close_{i}' for i in range(1, self.window_size + 1)]] # Target variable (next 'window_size' closing prices) - - - return X_train, y_train, X_test, y_test - - def predict_windows(self, window_size=30): - # Create and train the linear regression model for each day in the window - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - models = [] - for i in range(self.window_size): - model = LinearRegression() - model.fit(X_train, y_train[f'Close_{i+1}']) - models.append(model) - y_preds = [] - for model in models: - y_pred = model.predict(X_test) - y_preds.append(y_pred) - - avg_pred = np.mean(y_preds, axis=0) - plt.figure(figsize=(10, 5)) - plt.title(f"AVERGAGE Prediction") - plt.plot(y_test.index[window_size:], y_test[f'Close_{i+0}'][:-window_size], label='Actual') - plt.plot(y_test.index[window_size:], avg_pred[window_size:], label='Predicted', linestyle='--') - plt.legend() - plt.xlabel('Date') - plt.ylabel('Closing Price') - plt.grid(True) - plt.show() - - # Visualize the predictions - i=1 - plt.plot(y_test.index[i:], y_test[f'Close_{i+1}'][:-i], label='Actual') - for i in range(window_size): - plt.plot(y_test.index[i:], y_preds[i][i:], label='Predicted', linestyle='--') - # Add a legend for the plotted lines - plt.legend() - - # Show the plot - plt.show() - - # Plot the data - def plot_data(self, full_data, test_data, predictions, title="Data"): - fig, ax1 = plt.subplots(figsize=(10, 6)) - - # Plotting the actual data and predictions on the primary y-axis - ax1.plot(full_data['Close_Tomorrow'], label='Actual Data', color='blue') - ax1.plot(test_data.index, predictions, color='red', label='Predictions') - ax1.set_xlabel("Time") - ax1.set_ylabel("Value") - ax1.tick_params(axis='y', labelcolor='blue') - - # Adding legends and title - ax1.legend(loc='upper left') - # ax2.legend(loc='upper right') - plt.title(title) - - plt.show() - - def predict(self): - X_train, y_train, X_test, y_test = self.split_data('Close_Tomorrow', self.data) - - # Fit a Linear Regression model and make predictions - model = LinearRegression() - model.fit(X_train, y_train) - - # Make predictions on the testing data - predictions = model.predict(X_test) - self.model = model - - mse = mean_squared_error(y_test, predictions) - print(mse, 'MSE') - - # Plot the full data and predictions - self.plot_data(self.data, self.test_data, predictions) - - score= self.model.score(X_test, y_test) - print(score) - return predictions - -if __name__ == "__main__": - # Example usage - crypto_symbol = "ADA-USD" # Replace with your desired cryptocurrency symbol - window = 5 - cp = CryptoPrediction(crypto_symbol, window) - models = cp.predict_windows(window) - p_data = cp.predict() -132/134: -avg = np.mean(predictions, axis=0) -plt.plot(avg) -132/135: from utilsforecast.plotting import plot_series -132/136: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data['y'] = data['Close'] -132/137: -fig = plot_series(data, p_data) -fig -132/138: p_data -132/139: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -132/140: -from utilsforecast.plotting import plot_series -import lightgbm as lgb -from numba import njit -from window_ops.expanding import expanding_mean -from window_ops.rolling import rolling_mean -from mlforecast import MLForecast -from mlforecast.target_transforms import Differences -def hour_index(times): - return times % 24 -132/141: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -132/142: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data['y'] = data['Close'] -132/143: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data['y'] = data['Close'] -df = data -132/144: -lgb_params = { - 'verbosity': -1, - 'num_leaves': 512, -} - -fcst = MLForecast( - models={ - 'avg': lgb.LGBMRegressor(**lgb_params), - 'q75': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.75), - 'q25': lgb.LGBMRegressor(**lgb_params, objective='quantile', alpha=0.25), - }, - freq=1, - target_transforms=[Differences([24])], - lags=[1, 24], - lag_transforms={ - 1: [expanding_mean], - 24: [(rolling_mean, 48)], - }, - date_features=[hour_index], -) -fcst.fit(df) -132/145: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(df) -prep -132/146: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = data.index.values -data['y'] = data['Close'] -df = data -132/147: -fig = plot_series(data) -fig -132/148: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(df) -prep -132/149: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(data) -prep -132/150: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(data) -prep -132/151: data.index.values -132/152: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = pd.to_datetime(data.index.values) -pd.to_datetime -data['y'] = data['Close'] -df = data -132/153: data.index.values -132/154: -fig = plot_series(data) -fig -132/155: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(data) -prep -132/156: -data = cp.data -data['unique_id'] = crypto_symbol -data['ds'] = pd.to_datetime(data.index.values) -pd.to_datetime -data['y'] = data['Close'] -df = data -df['ds'] = pd.to_datetime(df['ds']) -df = df.set_index('ds') -132/157: data.index.values -132/158: -fig = plot_series(data) -fig -132/159: -fcst = MLForecast( - models=[], # we're not interested in modeling yet - freq=1, # our series have integer timestamps, so we'll just add 1 in every timestep - target_transforms=[Differences([24])], -) -prep = fcst.preprocess(data) -prep -133/1: -import plyvel - -# Open the LevelDB database -db = plyvel.DB('031321.ldb', create_if_missing=False) - -# Iterate over items in the database -for key, value in db.iterator(): - print(key, value) - -# Always close the database when you're done -db.close() -133/2: !pip install plyvel -133/3: -import plyvel - -# Open the LevelDB database -db = plyvel.DB('031321.ldb', create_if_missing=False) - -# Iterate over items in the database -for key, value in db.iterator(): - print(key, value) - -# Always close the database when you're done -db.close() -133/4: -import plyvel - -# Open the LevelDB database -db = plyvel.DB('', create_if_missing=False) - -# Iterate over items in the database -for key, value in db.iterator(): - print(key, value) - -# Always close the database when you're done -db.close() -133/5: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '/path/to/your/ldb/directory' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -133/6: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -133/7: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -133/8: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '../' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -133/9: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '../objects/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/1: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '../history/index/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/2: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'history/index/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/3: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path, create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/4: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/5: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/6: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/7: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = '/test/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/8: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/9: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB(directory_path,) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/10: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test',) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/11: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - ÷full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test',) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/12: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - # full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test',) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/13: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -# files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - # full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test',) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/14: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -# files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - # full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test/',) # create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/15: -import os -import plyvel - -# Specify your directory containing .ldb files -directory_path = 'test/005693.ldb' - -# List all files in the directory and sort them -# files = sorted(os.listdir(directory_path)) - -# Find the first .ldb file -ldb_file = next((file for file in files if file.endswith('.ldb')), None) - -if ldb_file: - # Construct the full path - # full_path = os.path.join(directory_path, ldb_file) - - # Open the LevelDB database - # Assuming that the .ldb file is part of a LevelDB database - - db = plyvel.DB('test/', create_if_missing=False) - - # Iterate over items in the database (or a part of it) - for key, value in db.iterator(): - print(key, value) - - # Close the database - db.close() -else: - print("No .ldb file found in the directory") -134/16: -import plyvel - -def read_leveldb(ldb_path): - try: - # Open the LevelDB database - db = plyvel.DB(ldb_path, create_if_missing=False) - - # Print the first few key-value pairs - for key, value in db.iterator(): - print(key, value) - break # Remove this line to iterate over more items - - db.close() - - except Exception as e: - print(f"An error occurred: {e}") - -if __name__ == "__main__": - ldb_file_path = 'test' # Replace with the path to your .ldb file - read_leveldb(ldb_file_path) -134/17: -import plyvel - -def read_leveldb(ldb_path): - try: - # Open the LevelDB database - db = plyvel.DB(ldb_path, create_if_missing=False) - - # Print the first few key-value pairs - for key, value in db.iterator(): - print(key, value) - break # Remove this line to iterate over more items - - db.close() - - except Exception as e: - print(f"An error occurred: {e}") - -if __name__ == "__main__": - ldb_file_path = 'test/005693.ldb' # Replace with the path to your .ldb file - read_leveldb(ldb_file_path) -134/18: -import plyvel - -def read_leveldb(ldb_path): - try: - # Open the LevelDB database - db = plyvel.DB(ldb_path)#, create_if_missing=False) - - # Print the first few key-value pairs - for key, value in db.iterator(): - print(key, value) - break # Remove this line to iterate over more items - - db.close() - - except Exception as e: - print(f"An error occurred: {e}") - -if __name__ == "__main__": - ldb_file_path = 'test/005693.ldb' # Replace with the path to your .ldb file - read_leveldb(ldb_file_path) -134/19: -import plyvel - -def read_leveldb(ldb_path): - try: - # Open the LevelDB database - db = plyvel.DB(ldb_path)#, create_if_missing=False) - - # Print the first few key-value pairs - for key, value in db.iterator(): - print(key, value) - break # Remove this line to iterate over more items - - db.close() - - except Exception as e: - print(f"An error occurred: {e}") - -if __name__ == "__main__": - ldb_file_path = 'test/' # Replace with the path to your .ldb file - read_leveldb(ldb_file_path) -134/20: -import plyvel - -def read_leveldb(directory_path): - try: - # Open the LevelDB database - db = plyvel.DB(directory_path, create_if_missing=False) - - # Print the first few key-value pairs - for key, value in db.iterator(): - print(key, value) - break # Remove this line to iterate over more items - - db.close() - - except Exception as e: - print(f"An error occurred: {e}") - -if __name__ == "__main__": - ldb_directory_path = 'test' # Replace with the path to your .ldb directory - read_leveldb(ldb_directory_path) -135/1: import main -135/2: -from consts import pools -from interest import get_historical_rates - - - -# Example, switch pool index for different pool -address = pools[1]["child"] -print(get_historical_rates(pools[1], address)) -135/3: -from consts import pools -from interest import get_historical_rates - - - -# Example, switch pool index for different pool -address = pools[1]["child"] -data = get_historical_rates(pools[1], address) -print(data) -135/4: data.keys() -135/5: data['projected_borrow_rates'] -135/6: data['projected_lender_apy'] -135/7: data['raw_rates'] -135/8: address -138/1: -import requests - -def get_api_data(api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None -138/2: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -if data is not None: - print("Data retrieved from the API:") - print(data) -else: - print("No data retrieved.") -138/3: -import requests - -def get_api_data(api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - -# Replace 'your_api_url' with the actual URL of the API you want to access -api_url = "your_api_url" -data = get_api_data(api_url) - -if data is not None: - print("Data retrieved from the API:") - print(data) -else: - print("No data retrieved.") -138/4: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -if data is not None: - print("Data retrieved from the API:") - print(data) -else: - print("No data retrieved.") -138/5: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data.keys() -138/6: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data -138/7: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data['items']['assets'] -138/8: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data -138/9: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data['item'] -138/10: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data['items'] -138/11: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data['items'][0] -138/12: -# Replace 'your_api_url' with the actual URL of the API you want to access - - -wallet_api_url = "https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD" -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -data = get_api_data(wallet_api_url) - -data['items'] -138/13: data['items'][1] -138/14: data['items'][1]['assets'] -138/15: -ls = [] -if ls: - True -138/16: -ls = [] -if ls: - True -else: - False -138/17: -ls = [] -if ls: - a = True -else: - a = False -a -139/1: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id): - self.api = api - self.token_id = token_id - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet, token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['token_id'] - if token == token_id: - return True - else: - return False -139/2: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679') -result = reader.find_token_in_wallet(wallet) -result -139/3: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id): - self.api = api - self.token_id = token_id - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token == self.token_id: - return True - else: - return False -139/4: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679') -result = reader.find_token_in_wallet(wallet) -result -139/5: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id): - self.api = api - self.token_id = token_id - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - else: - return False -139/6: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679') -result = reader.find_token_in_wallet(wallet) -result -139/7: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id): - self.api = api - self.token_id = token_id - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - print(items) - if token_id == self.token_id: - return True - else: - return False -139/8: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679') -result = reader.find_token_in_wallet(wallet) -result -139/9: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id): - self.api = api - self.token_id = token_id - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - print(items) - if token_id == self.token_id: - return True -139/10: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679') -result = reader.find_token_in_wallet(wallet) -result -139/11: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - print(items) - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) -139/12: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) -result -139/13: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) - -desc = reader.get_token_description() -139/14: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) - -desc = reader.get_token_description() -desc -139/15: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - # print(items) - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) -139/16: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) - -desc = reader.get_token_description() -desc -139/17: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - # print(items) - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - return data -139/18: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) - -desc = reader.get_token_description() -desc -139/19: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -139/20: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') - -result = reader.find_token_in_wallet(wallet) - -desc = reader.get_token_description() -desc - -reader.run(wallet) -139/21: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') -reader.run(wallet) -139/22: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id_url = 'https://api.ergo.aap.cornell.edu/api/v1/tokens/9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' - -reader = SigmaWalletReader(url, - token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', - token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens') -desc = reader.run(wallet) -139/23: -# Replace 'your_api_url' with the actual URL of the API you want to access - -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679', -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaWalletReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -139/24: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaWalletReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -139/25: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -140/1: -import requests - -class SigmaWalletReader: - def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): # token='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679'): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -140/2: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaWalletReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -140/3: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -142/1: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -142/2: -import requests - -class SigmaReader: - def __init__(self, api, token_id=None, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, url): - try: - # Send a GET request to the API - response = requests.get(url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -142/3: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -142/4: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -142/5: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -142/6: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -142/7: data.keys() -142/8: data.pools.keys() -142/9: data.pools. -142/10: data.pools -142/11: data['pools'] -142/12: data['pools'][1] -142/13: data['pools'][0] -142/14: data['pools'][0].keys() -142/15: -d = data['pools'][0] -for key in d.keys(): - print(d[key]) -142/16: -d = data['pools'][0] -for key in d.keys(): - print(d[key], '/n') -142/17: -d = data['pools'][0] -for key in d.keys(): - print(d[key], '\n') -142/18: -d = data['pools'][0] -for key in d.keys(): - print(key, d[key], '\n') -142/19: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -142/20: data['pools'][0].keys() -142/21: -d = data['pools'][0] -for key in d.keys(): - print(key, d[key], '\n') -144/1: -import requests - -class SigmaReader: - def __init__(self, api, token_id=None, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, url): - try: - # Send a GET request to the API - response = requests.get(url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -144/2: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -144/3: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -144/4: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/5: data['pools'][0].keys() -144/6: -d = data['pools'][0] -for key in d.keys(): - print(key, d[key], '\n') -144/7: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/8: -url = 'http://74.69.128.24:4000/api/' #pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/9: -url = 'http://74.69.128.24:4000/api/pools' #/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/10: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts' #/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/11: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners' #/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/12: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners' #/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/13: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners' #/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/14: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/15: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -144/16: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -145/1: -url='https://my.ergoport.dev/cgi-bin/mining/mining_all.html?a=9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/1: -import requests - -class SigmaReader: - def __init__(self, api, token_id=None, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, url): - try: - # Send a GET request to the API - response = requests.get(url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -146/2: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -146/3: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -146/4: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/5: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/6: data['pools'][0].keys() -146/7: -d = data['pools'][0] -for key in d.keys(): - print(key, d[key], '\n') -146/8: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/9: -url='https://my.ergoport.dev/cgi-bin/mining/mining_all.html?a=9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/10: -url='my.ergoport.dev/cgi-bin/mining/mining_all.html?a=9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -146/11: -url='https://my.ergoport.dev/cgi-bin/mining/mining_all.html?a=9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -147/1: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/1: -import requests - -class SigmaReader: - def __init__(self, api, token_id=None, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - self.api = api - self.token_id = token_id - self.token_ls = token_ls_url - - def get_api_data(self, url): - try: - # Send a GET request to the API - response = requests.get(url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def find_token_in_wallet(self, wallet,): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description - - def run(self, wallet): - - token_in_wallet = self.find_token_in_wallet(wallet) - if token_in_wallet: - description = self.get_token_description() - print('THE ADDRESS {} CONTAINS THE TOKEN {} WITH THE DESCRIPTION OF {}'.format(wallet, - self.token_id, - description)) - return description - else: - print('THE ADDRESS {} DOES NOT CONTAIN THE TOKEN {}'.format(wallet, self.token_id)) -148/2: -url = 'https://api.ergo.aap.cornell.edu/api/v1/boxes/unspent/byAddress/' -wallet = '9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZedzb9tD' -token_id='9f087ebb5d7baf7eb8f13b742e9a9b5b1b8d78b7a7f84d1f9b9d393f4888d679' -token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens' - -reader = SigmaReader(url, token_id,token_ls_url) -desc = reader.run(wallet) -148/3: -wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -desc = reader.run(wallet) -148/4: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/5: -url = 'http://74.69.128.24:4000/api/pools/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/6: data['pools'][0].keys() -148/7: -d = data['pools'][0] -for key in d.keys(): - print(key, d[key], '\n') -148/8: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/9: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/10: data['pendingShares'] -148/11: -miner_data = data[0] -miner_data['pendingShares'] -148/12: -miner_data = data[0] -miner_data['pendingShares'] -148/13: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/14: -miner_data = data[0] -miner_data['pendingShares'] -148/15: data['pendingShares'] -148/16: -url = 'http://74.69.128.24:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/17: data['performance'] -148/18: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/19: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data[0] -148/20: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/21: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/22: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data['poolStats'] -148/23: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data -148/24: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data.keys() -148/25: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data['pool'] -148/26: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/' -reader = SigmaReader('') -data = reader.get_api_data(url) -data['pool']['poolStats'] -148/27: data['pool'] -148/28: data['pool']['networkStats'] -148/29: data['pool']['topMiners'] -148/30: data['pool'] -148/31: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks' -reader = SigmaReader('') -data = reader.get_api_data(url) -data['pool']['poolStats'] -data['pool']['networkStats'] -data['pool']['topMiners'] -148/32: -url='http://74.69.128.24:4000/api/pools/ErgoSigmanauts/Blocks' -reader = SigmaReader('') -data = reader.get_api_data(url) -# data['pool']['poolStats'] -# data['pool']['networkStats'] -# data['pool']['topMiners'] -148/33: data -149/1: -from utils.reader import SigmaWalletReader -reader = SigmaWalletReader(config_path="../conf") -149/2: -data = reader.run_app() -data -149/3: -data = reader.run_app() -x, y, z = data -149/4: x -149/5: x[0] -149/6: block_df = pd.DataFrame(x[0]) -149/7: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -149/8: block_df = pd.DataFrame(x[0]) -150/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -150/2: -data = reader.run_app() -x, y, z = data -150/3: block_df = pd.DataFrame(x[0]) -150/4: -block_df = pd.DataFrame(x[0]) -block_df -150/5: y -150/6: x[1] -150/7: miner_found_blocks = pd.DataFrame(x[1]) -150/8: x[1] -150/9: -miner_found_blocks = pd.DataFrame([x[1]]) -miner_found_blocks -150/10: - -# Convert to DataFrame -df = pd.DataFrame.from_dict(x[1], orient='index', columns=['Value']) - -# Reset the index to make the keys a separate column -df.reset_index(inplace=True) - -# Rename columns as desired -df.columns = ['Key', 'Value'] -150/11: - -# Convert to DataFrame -df = pd.DataFrame.from_dict(x[1], orient='index', columns=['Value']) - -# Reset the index to make the keys a separate column -df.reset_index(inplace=True) - -# Rename columns as desired -df.columns = ['Key', 'Value'] -df -150/12: - -# Convert to DataFrame -df = pd.DataFrame.from_dict(x[1], orient='index', columns=['Value']) - -# Reset the index to make the keys a separate column -df.reset_index(inplace=True) - -# Rename columns as desired -df.columns = ['Miner', 'Number of Blocks Found'] -df -150/13: x[2] -150/14: average_effort = {'Average Effort': x[2]} -150/15: -average_effort = {'Average Effort': x[2]} -average_effort -150/16: df = pd.DataFrame(average_effort) -150/17: df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Value']) -150/18: -df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Value']) -df -150/19: -df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Value']) -df.reset_index(inplace=True) -df -150/20: -df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Average Effort']) -df.reset_index(inplace=True) -df -150/21: -df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Average Effort']) -# df.reset_index(inplace=True) -df -150/22: -df = pd.DataFrame.from_dict(average_effort, columns=['Average Effort']) -# df.reset_index(inplace=True) -df -150/23: -df = pd.DataFrame.from_dict(average_effort, orient='index', columns=['Average Effort']) -# df.reset_index(inplace=True) -df -151/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -151/2: -data = reader.run_app() -x, y, z = data -x, y, z -152/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -152/2: -data = reader.run_app() -x, y, z = data -x, y, z -152/3: -data = reader.run_app() -x, y, z = data -x -152/4: x -152/5: x.head() -152/6: x.head -152/7: -data = reader.run_app() -x, y, z = data -q, w, e = x -152/8: q -152/9: w -152/10: e -152/11: -data = reader.run_app() -x, y, z = data -y -152/12: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -153/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -153/2: -data = reader.run_app() -x, y, z = data -y -154/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -154/2: -data = reader.run_app() -x, y, z = data -y -155/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -155/2: -data = reader.run_app() -x, y, z = data -y -155/3: -data = reader.run_app() -x, y, z = data -z -155/4: -data = reader.run_app() -x, y, z = data -len(z) -155/5: x, y, z = z -155/6: z -155/7: x -155/8: y -155/9: z -155/10: x, y -155/11: -# x, y\ - -df1 = pd.DataFrame(list(x.items()), columns=['Key', 'Value']) -df2 = pd.DataFrame(list(y.items()), columns=['Key', 'Value']) - -# Concatenate the two DataFrames -df_combined = pd.concat([df1, df2], ignore_index=True) - -df_combined -155/12: -# x, y\ - -df1 = pd.DataFrame(list(x.items()), columns=['Key', 'Value']) -df2 = pd.DataFrame(list(y.items()), columns=['Key', 'Value']) - -# Concatenate the two DataFrames -df_combined = pd.concat([df1, df2], ignore_index=True) -df_combined.columns = ['Pool Stats', 'Values') -df_combined -155/13: -# x, y\ - -df1 = pd.DataFrame(list(x.items()), columns=['Key', 'Value']) -df2 = pd.DataFrame(list(y.items()), columns=['Key', 'Value']) - -# Concatenate the two DataFrames -df_combined = pd.concat([df1, df2], ignore_index=True) -df_combined.columns = ['Pool Stats', 'Values'] -df_combined -155/14: z -155/15: pd.Dataframe(z) -155/16: pd.DataFrame(z) -156/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -156/2: -data = reader.run_app() -x, y, z = data -156/3: z[0] -156/4: z[1] -156/5: mining_data_df = reader.get_mining_stats() -156/6: -mining_data_df = reader.get_mining_stats() -mining_data_df -156/7: -mining_data_df = reader.get_mining_stats() -mining_data_df[:-1] -156/8: -mining_data_df = reader.get_mining_stats() -mining_data_df -156/9: mining_data_df[-1] -156/10: mining_data_df[-1:] -156/11: mining_data_df[-1:]['Values'] -156/12: mining_data_df[-1:]['Values'].keys() -156/13: mining_data_df[-1:]['Values'] -156/14: mining_data_df[-1:]['Values'][0] -156/15: mining_data_df[-1:]['Values'] -156/16: mining_data_df[-1:]['Values'].values() -157/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -157/2: -mining_data_df = reader.get_mining_stats() -mining_data_df -158/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -158/2: -mining_data_df = reader.get_mining_stats() -mining_data_df -159/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -159/2: -mining_data_df = reader.get_mining_stats() -mining_data_df -160/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -160/2: -mining_data_df = reader.get_mining_stats() -mining_data_df -160/3: -mining_data_df = reader.get_mining_stats() -mining_data_df[1] -161/1: -from utils.reader import SigmaWalletReader -import pandas as pd -reader = SigmaWalletReader(config_path="../conf") -161/2: -mining_data_df = reader.get_mining_stats() -mining_data_df[1] -163/1: -from pycoingecko import CoinGeckoAPI -cg = CoinGeckoAPI() - -# Fetch current price of Bitcoin (BTC) and Ergo (ERG) in USD -prices = cg.get_price(ids=['bitcoin', 'ergo'], vs_currencies='usd') - -btc_price = prices['bitcoin']['usd'] -erg_price = prices['ergo']['usd'] - -print(f"BTC Price: ${btc_price}") -print(f"ERG Price: ${erg_price}") -164/1: -from pycoingecko import CoinGeckoAPI -cg = CoinGeckoAPI() - -# Fetch current price of Bitcoin (BTC) and Ergo (ERG) in USD -prices = cg.get_price(ids=['bitcoin', 'ergo'], vs_currencies='usd') - -btc_price = prices['bitcoin']['usd'] -erg_price = prices['ergo']['usd'] - -print(f"BTC Price: ${btc_price}") -print(f"ERG Price: ${erg_price}") -166/1: -from pycoingecko import CoinGeckoAPI -cg = CoinGeckoAPI() -166/2: cg.get_coins_list() -166/3: prices = cg.get_price(ids=['rosen-bridge', 'ergo'], vs_currencies='usd') -166/4: prices -166/5: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='usd') -166/6: prices -166/7: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='btc') -166/8: prices -166/9: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='erg') -166/10: prices -166/11: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='ergo') -166/12: prices -166/13: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='usd') -166/14: prices -166/15: df = DataFrame(prices) -166/16: -from pycoingecko import CoinGeckoAPI -from pandas import DataFrame -cg = CoinGeckoAPI() -166/17: prices = cg.get_price(ids=['rosen-bridge', 'ergo', 'spectrum-finance'], vs_currencies='usd') -166/18: df = DataFrame(prices) -166/19: -df = DataFrame(prices) -df -167/1: from polls.models import Choice, Question -167/2: Question.objects.all() -167/3: from django.utils import timezone -167/4: q = Question(question_text="What's new?", pub_date=timezone.now()) -167/5: q.save() -167/6: q.id -167/7: q.question_text -167/8: q.pub_date -167/9: q.question_text = "What's up?" -167/10: q.save -167/11: q.save() -167/12: Question.objects.all() -168/1: from polls.models import Choice, Question -168/2: Question.objects.all() -168/3: Question.objects.filter(id=1) -168/4: Question.objects.filter(question_text__startswith="What") -168/5: current_year = timezone.now().year -168/6: from django.utils import timezone -168/7: current_year = timezone.now().year -168/8: Question.objects.get(pub_date__year=current_year) -168/9: Question.objects.get(pk=1) -168/10: q = Question.objects.get(pk=1) -168/11: q.was_published_recently() -168/12: q.choice_set.all() -168/13: q.choice_set.create(choice_text="Not much", votes=0) -168/14: q.choice_set.create(choice_text="The sky", votes=0) -168/15: c = q.choice_set.create(choice_text="Just hacking again", votes=0) -168/16: c.question -168/17: q.choice_set.all() -169/1: from reader import SigmaWalletReader -169/2: from ../reader import SigmaWalletReader -170/1: from reader import SigmaWalletReader -170/2: from utils.reader import SigmaWalletReader -169/3: from utils.reader import SigmaWalletReader -169/4: from utils.reader import SigmaWalletReader -169/5: from utils.reader import SigmaWalletReader -171/1: from utils.reader import SigmaWalletReader -171/2: 0+0 -171/3: reader = SigmaWalletReader(config_path="../conf") -171/4: reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -171/5: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -171/6: -miners = {} -for sample in data: - miner[sample['miner']: 0] -171/7: -miners = {} -for sample in data: - miners[sample['miner']: 0] -171/8: -miners = {} -for sample in data: - miners{sample['miner']: 0} -171/9: -miners = {} -for sample in data: - miners[sample['miner'] = 0 -171/10: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -171/11: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -miners -171/12: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - data = reader.get_api_data(url) -data -171/13: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - data = reader.get_api_data(url) - miners[key] = data['pendingShares'] -miners -171/14: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -171/15: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -171/16: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -171/17: -import pandas as pd -df = pd.DataFrame(rewards) -171/18: -import pandas as pd -df = pd.DataFrame.from_dict(rewards) -171/19: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index') -171/20: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index') -df -171/21: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index', 'columns':['Miner', 'Reward']) -df -171/22: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index', 'columns'= ['Miner', 'Reward']) -df -171/23: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index', columns= ['Miner', 'Reward']) -df -171/24: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, - columns= ['Miner', 'Reward']) -df -171/25: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='columns', - columns= ['Miner', 'Reward']) -df -171/26: -import pandas as pd -df = pd.DataFrame.from_dict(rewards, orient='index', - columns= ['Miner', 'Reward']) -df -171/27: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -171/28: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4Xhqys' -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -171/29: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4Xhqys' -data = reader.get_api_data(url) -data -171/30: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4Xhqys' -data = reader.get_api_data(url) -data['performance'] -171/31: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4Xhqys' -data = reader.get_api_data(url) -data -171/32: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4Xhqys' -data = reader.get_api_data(url) -data['performanceSamples'] -171/33: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -data['performanceSamples'] -171/34: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -data['performanceSamples'] -171/35: pd -171/36: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -171/37: pd.DataFrame(samples) -171/38: -def convert_to_dataframe(data): - # Initialize an empty list to hold the flattened data - flattened_data = [] - - # Iterate over each entry in the data - for entry in data: - created_time = entry['created'] - - # Iterate over each worker in the 'workers' dictionary - for worker_name, metrics in entry['workers'].items(): - # Create a flat dictionary for each worker - flat_entry = { - 'created': created_time, - 'worker': worker_name, - 'hashrate': metrics['hashrate'], - 'sharesPerSecond': metrics['sharesPerSecond'] - } - # Append the flat dictionary to the list - flattened_data.append(flat_entry) - - # Convert the list of flat dictionaries to a DataFrame - return pd.DataFrame(flattened_data) - -# Create the DataFrame -df = convert_to_dataframe(samples) -df -171/39: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -173/1: from utils.reader import SigmaWalletReader -173/2: reader = SigmaWalletReader(config_path="../conf") -173/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -173/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -173/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -173/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -173/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -173/8: SigmaWalletReader.get_miner_samples('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -173/9: df = SigmaWalletReader.get_miner_samples('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -174/1: from utils.reader import SigmaWalletReader -174/2: reader = SigmaWalletReader(config_path="../conf") -174/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -174/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -174/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -174/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -174/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -174/8: df = SigmaWalletReader.get_miner_samples('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -176/1: from utils.reader import SigmaWalletReader -176/2: reader = SigmaWalletReader(config_path="../conf") -176/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -176/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -176/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -176/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -176/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -176/8: df = SigmaWalletReader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -176/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -177/1: from utils.reader import SigmaWalletReader -177/2: reader = SigmaWalletReader(config_path="../conf") -177/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -177/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -177/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -177/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -177/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -177/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -178/1: from utils.reader import SigmaWalletReader -178/2: reader = SigmaWalletReader(config_path="../conf") -178/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -178/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -178/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -178/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -178/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -178/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -178/9: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -178/10: df.empty -178/11: pd.DataFrame({'created': 0, 'hashrate': 0}) -178/12: pd.DataFrame({'created': 0, 'hashrate': 0}, index=0) -178/13: pd.DataFrame({'created': 0, 'hashrate': 0}, index=1) -178/14: pd.DataFrame([0,0], columns=['a','b']) -178/15: pd.DataFrame([0,0], columns=['a','b'], index=1) -178/16: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d) -178/17: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d, index=1) -178/18: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d, orient='index') -178/19: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d, orient='columns') -178/20: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d, orient='columns', columns=['a', 'b']) -178/21: -d = {'a': 1, - 'b': 2} -pd.DataFrame.from_dict(d, columns=['a', 'b']) -178/22: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -178/23: import random -178/24: random.randint(0,1) -178/25: random.randint(0,5) -178/26: random.randrange(0,5) -178/27: random.randrange(0,5) -178/28: random.randrange(0,5) -178/29: random.randrange(0,5) -178/30: -import numpy as np -np.random.uniform(low=0.5, high=13.3, size=(50,)) -178/31: -import numpy as np -np.random.uniform(low=0.3, high=5, size=(50,)) -178/32: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [range(0, 50)] -178/33: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [range(0, 50)] -x, y -178/34: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] -x, y -178/35: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df.plot() -178/36: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df.plot(x=x, y=y) -178/37: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df.plot(x=df.x, y=df.y) -178/38: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -178/39: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df -178/40: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df.plot(y=df.y) -178/41: -import numpy as np -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df -178/42: -import numpy as np -import matplotlib.pyplot as plt -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -plt.figure(figsize=(8, 6)) # You can adjust the figure size as needed -plt.plot(df['x'], df['y'], marker='o', linestyle='-', color='b') # marker, linestyle, and color are customizable -plt.title('Plot of x vs y') # Adds a title to your plot -plt.xlabel('x values') # Label for the x-axis -plt.ylabel('y values') # Label for the y-axis -plt.grid(True) # Adds a grid for better readability -plt.show() # Displays the plot -178/43: -import numpy as np -import matplotlib.pyplot as plt -y = np.random.uniform(low=0.3, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/44: -import numpy as np -import matplotlib.pyplot as plt -y = np.random.uniform(low=0.001, high=5, size=(50,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/45: -import numpy as np -import matplotlib.pyplot as plt -y = np.random.uniform(low=0.001, high=5, size=(10000,)) -x = [*range(0, 50)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/46: -import numpy as np -import matplotlib.pyplot as plt -n = 100000 -y = np.random.uniform(low=0.001, high=5, size=(n,)) -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/47: -import numpy as np -import matplotlib.pyplot as plt -n = 1000 -y = np.random.uniform(low=0.001, high=5, size=(n,)) -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/48: -import numpy as np -import matplotlib.pyplot as plt -n = 1000 -y = np.random.uniform(low=0.001, high=4, size=(n,)) -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/49: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 1000 # number of random variables -y = generate_random_variable_list(n) -print(y) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/50: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 1000 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/51: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 100 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/52: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -178/53: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -180/1: from utils.reader import SigmaWalletReader -181/1: from utils.reader import SigmaWalletReader -181/2: reader = SigmaWalletReader(config_path="../conf") -181/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -181/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -181/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -181/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -181/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -181/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -181/9: df.empty -181/10: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -181/11: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -181/12: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -181/13: random.randrange(0,5) -181/14: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -data = reader.get_api_data(url) -data -181/15: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -data = reader.get_api_data(url) -data.keys() -181/16: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -data.keys() -181/17: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/18: pool['coin'] -181/19: pool['paymentProcessing'] -181/20: pool['clientConnectionTimeout'] -181/21: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/22: pool['poolFeePercent'] -181/23: pool['poolStats'] -181/24: pool['paymentProcessing'] -181/25: pool['jobRebroadcastTimeout'] -181/26: pool['blockRefreshInterval'] -181/27: pool['poolFeePercent'] -181/28: pool['ports'] -181/29: pool['address'] -181/30: pool['addressInfoLink'] -181/31: pool['poolStats'] -181/32: pool['networkStats'] -181/33: pool['topMiners''] -181/34: pool['topMiners'] -181/35: pool['totalPaid'] -181/36: pool['totalBlocks'] -181/37: pool['lastPoolBlockTime'] -181/38: pool['poolEffort'] -181/39: -payment_data = pool['paymentProcessing'] -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/40: payment_data -181/41: payment_data.pop('enable') -181/42: del payment_data('enable') -181/43: del payment_data('enable') -181/44: -payment_data = pool['paymentProcessing'] -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/45: del payment_data('enable') -181/46: del payment_data['enable'] -181/47: payment_data -181/48: del payment_data['enabled'] -181/49: -del payment_data['enabled'] -payment_data -181/50: -payment_data = pool['paymentProcessing'] -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/51: payment_data -181/52: -del payment_data['enabled'] -payment_data -181/53: -payment_data = pool['paymentProcessing'] -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/54: payment_data -181/55: -del payment_data['enabled'] -payment_data -181/56: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/57: pool['poolEffort'] -181/58: -payment_data = pool['paymentProcessing'] -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/59: payment_data -181/60: -del payment_data['enabled'] -payment_data -181/61: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/62: pool['poolEffort'] -181/63: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/64: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/65: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -181/66: pool['poolEffort'] -181/67: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] - -pool_fee = pool['poolFeePercent'] -port_data = pool['ports'] # likely just use the port number and if TLS is true or not and why to use or not -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -181/68: payment_data -181/69: -del payment_data['enabled'] -payment_data -181/70: pool_fee -181/71: port_data -181/72: -modified_port_data = {} -for port in port_data: - temp = port_data[port] - modified_port_data[port] = tls -modified_port_data -181/73: -modified_port_data = {} -for port in port_data: - temp = port_data[port] - modified_port_data[port] = 'TLS: {}'.format(temp['tls']) -modified_port_data -181/74: -modified_port_data = {} -for port in port_data: - temp = port_data[port] - high_or_low - if 'pikes_peak' in temp['name']: - high_or_low = '>10GH/s' - else: - high_or_low = '<10GH/s - - modified_port_data[port] = '{} TLS: {}'.format(high_or_low, temp['tls']) -modified_port_data -181/75: -modified_port_data = {} -for port in port_data: - temp = port_data[port] - high_or_low - if 'pikes_peak' in temp['name']: - high_or_low = '>10GH/s' - else: - high_or_low = '<10GH/s' - - modified_port_data[port] = '{} TLS: {}'.format(high_or_low, temp['tls']) -modified_port_data -181/76: -modified_port_data = {} -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = '>10GH/s' - else: - high_or_low = '<10GH/s' - - modified_port_data[port] = '{} TLS: {}'.format(high_or_low, temp['tls']) -modified_port_data -181/77: -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append(temp['name'], port, high_or_low, temp['tls']) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS') -df -181/78: -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append(temp['name'], port, high_or_low, temp['tls']) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS')) -df -181/79: -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append(temp['name'], port, high_or_low, temp['tls']) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -181/80: -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -181/81: pool_stats -181/82: net_stats -181/83: last_block_found -181/84: total_paid -181/85: total_blocks -181/86: import dash -181/87: help(dash.html.Img) -182/1: from utils.reader import SigmaWalletReader -183/1: from utils.reader import SigmaWalletReader -183/2: reader = SigmaWalletReader(config_path="../conf") -183/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -183/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -183/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -183/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -183/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -183/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -183/9: df.empty -183/10: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -183/11: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -183/12: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -183/13: random.randrange(0,5) -183/14: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -183/15: pool['poolEffort'] -183/16: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -183/17: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -183/18: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -183/19: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -183/20: total_blocks -183/21: import dash -183/22: help(dash.html.Img) -183/23: net_stats -183/24: payment_data -183/25: pool_stats -183/26: reader.get_front_page_data() -184/1: from utils.reader import SigmaWalletReader -184/2: reader = SigmaWalletReader(config_path="../conf") -184/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -184/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -184/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -184/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -184/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -184/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -184/9: df.empty -184/10: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -184/11: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -184/12: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -184/13: random.randrange(0,5) -184/14: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -184/15: pool['poolEffort'] -184/16: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -184/17: payment_data -184/18: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -184/19: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -184/20: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -184/21: pool_stats -184/22: import dash -184/23: reader.get_front_page_data() -185/1: from utils.reader import SigmaWalletReader -185/2: reader = SigmaWalletReader(config_path="../conf") -185/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -185/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -185/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -185/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -185/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -185/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -185/9: df.empty -185/10: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -185/11: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -185/12: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -185/13: random.randrange(0,5) -185/14: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -185/15: pool['poolEffort'] -185/16: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -185/17: payment_data -185/18: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -185/19: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -185/20: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -185/21: pool_stats -185/22: import dash -185/23: reader.get_front_page_data() -185/24: data = reader.get_front_page_data() -185/25: data['poolHashrate'] = data['poolHashrate'] / 1e16 -185/26: -data['poolHashrate'] = data['poolHashrate'] / 1e16 -data['poolHashrate'] -185/27: data = reader.get_front_page_data() -185/28: -data['poolHashrate'] = data['poolHashrate'] / 1e6 -data['poolHashrate'] -185/29: data = reader.get_front_page_data() -185/30: -data['poolHashrate'] = data['poolHashrate'] / 1e9 -data['poolHashrate'] -185/31: data -185/32: last_block_found -185/33: -from datetime import datetime - -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - -date_time_obj = datetime.strptime(last_block_found, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - -print(f"The converted date and time is: {readable_format}") -185/34: readable_format -185/35: -from datetime import datetime - -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' -l = data['lastNetworkBlockTime'] -date_time_obj = datetime.strptime(l, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - -print(f"The converted date and time is: {readable_format}") -185/36: -from datetime import datetime - -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' -l = data['lastNetworkBlockTime'] -date_time_obj = datetime.strptime(l, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - -print(f"The converted date and time is: {readable_format}") -185/37: -from datetime import datetime - -input_string = data['lastNetworkBlockTime'] -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - -date_time_obj = datetime.strptime(input_string, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - -print(f"The converted date and time is: {readable_format}") -185/38: -from datetime import datetime - -input_string = data['lastNetworkBlockTime'] -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - -date_time_obj = datetime.strptime(input_string, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - - -print(f"The converted date and time is: {readable_format}") -187/1: from utils.reader import SigmaWalletReader -187/2: reader = SigmaWalletReader(config_path="../conf") -187/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -187/4: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -187/5: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -187/6: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -187/7: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -187/8: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -187/9: df.empty -187/10: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -187/11: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -187/12: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('Blocks Found') -plt.ylabel('y and z') -plt.title('Y - Effort, Z - Effort Feeback Response') -plt.legend() -plt.show() -187/13: random.randrange(0,5) -187/14: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -187/15: pool['poolEffort'] -187/16: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -187/17: payment_data -187/18: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -187/19: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -187/20: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -187/21: pool_stats -187/22: import dash -187/23: data = reader.get_front_page_data() -187/24: from utils.reader import SigmaWalletReader -187/25: reader = SigmaWalletReader(config_path="../conf") -187/26: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -188/1: from utils.reader import SigmaWalletReader -188/2: reader = SigmaWalletReader(config_path="../conf") -188/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -188/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -190/1: from utils.reader import SigmaWalletReader -190/2: reader = SigmaWalletReader(config_path="../conf") -190/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -190/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -190/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -190/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -190/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -190/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -190/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -190/10: df.empty -190/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -190/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -190/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -190/14: random.randrange(0,5) -190/15: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -190/16: pool['poolEffort'] -190/17: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -190/18: payment_data -190/19: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -190/20: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -190/21: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -190/22: pool_stats -190/23: import dash -190/24: data = reader.get_front_page_data() -190/25: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -190/26: data -190/27: last_block_found -190/28: -from datetime import datetime - -input_string = data['lastNetworkBlockTime'] -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - -date_time_obj = datetime.strptime(input_string, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - - -print(f"The converted date and time is: {readable_format}") -190/29: df -190/30: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].cumsum() / df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -190/31: df -190/32: -df.melt(id_vars=['x', 'y']) -df -190/33: -df.melt(id_vars=['x', 'y'], values=['x', 'y']) -df -190/34: -df.melt(id_vars=['x', 'y'], value=['x', 'y']) -df -190/35: -df.melt(id_vars=['x', 'y'], value_vars=['x', 'y']) -df -190/36: df.melt(id_vars=['x', 'y'], value_vars=['x', 'y']) -190/37: -n = df.melt(id_vars=['x', 'y'], value_vars=['x', 'y']) -n -190/38: -n = df.melt(id_vars=['x', 'y']) -n -190/39: -n = df.melt(id_vars=['z', 'y']) -n -190/40: -n = df.melt(id_vars=['x']) -n -190/41: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().count() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -190/42: df -190/43: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -190/44: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -192/1: from utils.reader import SigmaWalletReader -193/1: from utils.reader import SigmaWalletReader -193/2: reader = SigmaWalletReader(config_path="../conf") -193/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -193/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -193/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -193/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -193/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -193/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -193/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -193/10: df.empty -193/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -193/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -193/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -193/14: df -193/15: df -193/16: -n = df.melt(id_vars=['x']) -n -193/17: random.randrange(0,5) -193/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -193/19: pool['poolEffort'] -193/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -193/21: payment_data -193/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -193/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -193/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -193/25: pool_stats -193/26: import dash -193/27: data = reader.get_front_page_data() -193/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -193/29: data -193/30: last_block_found -193/31: -from datetime import datetime - -input_string = data['lastNetworkBlockTime'] -format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - -date_time_obj = datetime.strptime(input_string, format_string) -readable_format = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - - -print(f"The converted date and time is: {readable_format}") -193/32: df = reader.get_all_miner_data() -193/33: -df = reader.get_all_miner_data() -df -194/1: from utils.reader import SigmaWalletReader -194/2: reader = SigmaWalletReader(config_path="../conf") -194/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -194/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -194/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -194/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -194/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -194/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -194/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -194/10: df.empty -194/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -194/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -194/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -194/14: df -194/15: df -194/16: -n = df.melt(id_vars=['x']) -n -194/17: random.randrange(0,5) -194/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -194/19: pool['poolEffort'] -194/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -194/21: payment_data -194/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -194/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -194/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -194/25: pool_stats -194/26: import dash -194/27: data = reader.get_front_page_data() -194/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -194/29: data -194/30: last_block_found -194/31: readable_format -194/32: -df = reader.get_all_miner_data() -df -194/33: df[df.wallet == '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'] -194/34: -df = reader.get_all_miner_data() -df['datetime'] = pd.to_datetime(df['created']) -df_sorted = df.sort_values(by='datetime', ascending=False) -latest_data = df_sorted.iloc[0] -latest_data -194/35: -df = reader.get_all_miner_data() -df['datetime'] = pd.to_datetime(df['created']) -df_sorted = df.sort_values(by='datetime', ascending=False) -df_sorted -194/36: -df = reader.get_all_miner_data() -df['datetime'] = pd.to_datetime(df['created']) -df_sorted = df.sort_values(by='datetime', ascending=False) -df_sorted['created'] -194/37: -df = reader.get_all_miner_data() -df['datetime'] = pd.to_datetime(df['created']) -df_sorted = df.sort_values(by='datetime', ascending=False) -min(df_sorted['created']) -194/38: -df = reader.get_all_miner_data() -df['datetime'] = pd.to_datetime(df['created']) -df_sorted = df.sort_values(by='datetime', ascending=False) -max(df_sorted['created']) -194/39: -df = reader.get_all_miner_data() -latest_time = max(df_sorted['created']) -latest_df = df[df.created == latest_time] -194/40: latest_df[latest_df.wallet == '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'] -195/1: from utils.reader import SigmaWalletReader -195/2: reader = SigmaWalletReader(config_path="../conf") -195/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -195/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -195/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -195/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -195/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -195/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -195/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -195/10: df.empty -195/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -195/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -195/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -195/14: df -195/15: df -195/16: -n = df.melt(id_vars=['x']) -n -195/17: random.randrange(0,5) -195/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -195/19: pool['poolEffort'] -195/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -195/21: payment_data -195/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -195/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -195/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -195/25: pool_stats -195/26: import dash -195/27: data = reader.get_front_page_data() -195/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -195/29: data -195/30: last_block_found -195/31: -df = reader.get_all_miner_data() -latest_time = max(df_sorted['created']) -latest_df = df[df.created == latest_time] -195/32: df = reader.get_all_miner_data() -195/33: df[df.wallet == '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'] -195/34: -df = reader.get_all_miner_data() -df -195/35: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 2e12 # Example difficulty -network_hashrate = 1e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 1e14 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/36: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort / 100 - -# Example usage: -network_difficulty = 2e12 # Example difficulty -network_hashrate = 1e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 1e14 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/37: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort / 100 - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/38: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/39: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 *6 * 48 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/40: -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param time_since_last_block: Time since the last block was found by the network (in seconds). - :return: The estimated mining effort for the pool. - """ - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -time_since_last_block = 600 *6 * 24 * 7 # Example time since last block in seconds (10 minutes) - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, time_since_last_block) -print(f"The estimated mining effort for the pool is: {effort}") -195/41: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - last_block_time = datetime.strptime(last_block_timestamp, '%Y-%m-%dT%H:%M:%SZ') - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = '2024-03-24T20:00:00Z' # Example timestamp of the last block - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -195/42: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - last_block_time = datetime.strptime(last_block_timestamp, '%Y-%m-%dT%H:%M:%SZ') - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = '2024-03-19T20:00:00Z' # Example timestamp of the last block - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -195/43: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = "%Y-%m-%dT%H:%M:%SZ" - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"Mining Effort: {effort}") -last_block_timestamp = '2024-03-19T20:00:00Z' # Example timestamp of the last block - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -195/44: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = "%Y-%m-%dT%H:%M:%SZ" - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -195/45: -from datetime import datetime - -date_time_str = '2024-03-19 04:19:20' -format = '%Y-%m-%dT%H:%M:%S' -date_time_obj = datetime.strptime(date_time_str, format) - -print(date_time_obj) -195/46: -from datetime import datetime - -date_time_str = '2024-03-19 04:19:20' -format = '%Y-%m-%d %H:%M:%S' # Added a space between '%d' and '%H' -date_time_obj = datetime.strptime(date_time_str, format) - -print(date_time_obj) -195/47: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -196/1: from utils.reader import SigmaWalletReader -196/2: reader = SigmaWalletReader(config_path="../conf") -196/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -196/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -196/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -196/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -196/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -196/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -196/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -196/10: df.empty -196/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -196/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -196/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -196/14: df -196/15: df -196/16: -n = df.melt(id_vars=['x']) -n -196/17: random.randrange(0,5) -196/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -196/19: pool['poolEffort'] -196/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -196/21: payment_data -196/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -196/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -196/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -196/25: pool_stats -196/26: import dash -196/27: data = reader.get_front_page_data() -196/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -196/29: data -196/30: last_block_found -196/31: -df = reader.get_all_miner_data() -df -196/32: -df = reader.get_all_miner_data('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -df -197/1: from utils.reader import SigmaWalletReader -197/2: reader = SigmaWalletReader(config_path="../conf") -197/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -197/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -197/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -197/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -197/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -197/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -197/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -197/10: df.empty -197/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -197/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -197/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -197/14: df -197/15: df -197/16: -n = df.melt(id_vars=['x']) -n -197/17: random.randrange(0,5) -197/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -197/19: pool['poolEffort'] -197/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -197/21: payment_data -197/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -197/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -197/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -197/25: pool_stats -197/26: import dash -197/27: data = reader.get_front_page_data() -197/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -197/29: data -197/30: last_block_found -197/31: -df = reader.get_all_miner_data('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -df -197/32: df[df.wallet == '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'] -198/1: from utils.reader import SigmaWalletReader -198/2: reader = SigmaWalletReader(config_path="../conf") -198/3: -data = reader.get_api_data('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/') -data -198/4: -miner_ls = [] -for sample in data: - miner_ls.append(sample['miner']) - - -miner_ls -198/5: -miners = {} -for sample in data: - miners[sample['miner']] = 0 -for key in miners.keys(): - url = '{}/{}'.format('http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners', key) - sample = reader.get_api_data(url) - miners[key] = sample['pendingShares'] -miners -198/6: -# Total of all values -total = sum(miners.values()) - -# Assume a reward variable, say 10000 for this example -reward = 30 - -# Calculate the percentage for each key based on its value and then determine the reward based on this percentage -rewards = {key: (value / total) * reward for key, value in miners.items()} - -rewards -198/7: -import pandas as pd -rewards_df = pd.DataFrame(list(rewards.items()), columns=['miner', 'reward']) -rewards_df -198/8: -url = 'http://15.204.211.130:4000/api/pools/ErgoSigmanauts/miners/9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk' -data = reader.get_api_data(url) -samples = data['performanceSamples'] -samples -198/9: df = reader.get_miner_samples(wallet='9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -198/10: df.empty -198/11: -d = {'a': [1], - 'b': [2]} -pd.DataFrame.from_dict(d) -198/12: -import plotly.express as px - -fig = px.line(df, x='created', y='hashrate', color='worker', title='Hashrate Over Time for Each Worker') -fig.show() -198/13: -import numpy as np -import matplotlib.pyplot as plt - -import random - -def generate_random_variable_list(n): - random_variable_list = [] - for i in range(n): - random_variable = random.uniform(0.001, 5) - random_variable_list.append(random_variable) - return random_variable_list - -n = 10 # number of random variables -y = generate_random_variable_list(n) - -x = [*range(0, n)] - -df = pd.DataFrame({'x': x, 'y':y}) -df['z'] = df['y'].expanding().mean() - - -plt.plot(df['x'], df['y'], label='y') -plt.plot(df['x'], df['z'], label='z') -plt.xlabel('x') -plt.ylabel('y and z') -plt.title('Plotting y and z over x') -plt.legend() -plt.show() -198/14: df -198/15: df -198/16: -n = df.melt(id_vars=['x']) -n -198/17: random.randrange(0,5) -198/18: -url ='http://15.204.211.130:4000/api/pools/ErgoSigmanauts' - -pool = reader.get_api_data(url)['pool'] -pool.keys() -198/19: pool['poolEffort'] -198/20: -payment_data = pool['paymentProcessing'] -del payment_data['enabled'] -del payment_data['payoutSchemeConfig'] -del payment_data['extra'] -198/21: payment_data -198/22: -port_data = pool['ports'] - -ls = [] -for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) -df = pd.DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) -df -198/23: -pool_fee = pool['poolFeePercent'] -pool_stats = pool['poolStats'] -net_stats = pool['networkStats'] -total_paid = pool['totalPaid'] -total_blocks = pool['totalBlocks'] -last_block_found = pool['lastPoolBlockTime'] -pool_effort = pool['poolEffort'] -198/24: -net_stats -del net_stats['connectedPeers'] -del net_stats['rewardType'] -del net_stats['networkType'] -198/25: pool_stats -198/26: import dash -198/27: data = reader.get_front_page_data() -198/28: -data['poolHashrate'] = data['poolHashrate'] / 1e9 #GIGA -data['poolHashrate'] -198/29: data -198/30: last_block_found -198/31: -df = reader.get_all_miner_data('9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk') -df -198/32: df[df.wallet == '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'] -198/33: -miners = reader.get_miner_ls() -data = [] -for miner in miners: - temp = self.get_miner_samples(miner) -198/34: -miners = reader.get_miner_ls() -data = [] -for miner in miners: - temp = reader.get_miner_samples(miner) -198/35: temp -198/36: -miners = reader.get_miner_ls() -data = [] -for miner in miners: - temp = reader.get_miner_samples(miner) - data.append(temp) - -df = pd.concat(data) -198/37: df -198/38: -ls = [] -for date in df.created.unique(): - temp = df[df.created == date] - ls.append([date, temp.hashrate.sum()]) - -n = pd.DataFrame(ls, columns=['Date', 'Hashrate']) -198/39: n -198/40: -ls = [] -for date in df.created.unique(): - temp = df[df.created == date] - ls.append([date, temp.hashrate.sum() /1e9]) - -n = pd.DataFrame(ls, columns=['Date', 'Hashrate']) -198/41: n -198/42: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 14e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -198/43: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 12.4e15 # Example total network hash rate (1 PH/s) -pool_hashrate = 15e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -200/1: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 12.4e12 # Example total network hash rate (1 PH/s) -pool_hashrate = 15e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-19 04:19:20" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -200/2: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.73e15 # Example difficulty -network_hashrate = 12.4e12 # Example total network hash rate (1 PH/s) -pool_hashrate = 15e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-31 07:40:29" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -200/3: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.83e15 # Example difficulty -network_hashrate = 15.4e12 # Example total network hash rate (1 PH/s) -pool_hashrate = 13e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-31 07:40:29" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -200/4: -from datetime import datetime -import pytz - -def calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (pool_hashrate / network_hashrate) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block - - return effort - -# Example usage: -network_difficulty = 1.83e15 # Example difficulty -network_hashrate = 15.4e12 # Example total network hash rate (1 PH/s) -pool_hashrate = 13.3e9 # Example pool hash rate (100 TH/s) -last_block_timestamp = "2024-03-31 07:40:29" - -effort = calculate_mining_effort(network_difficulty, network_hashrate, pool_hashrate, last_block_timestamp) -print(f"The estimated mining effort for the pool since the last block is: {effort}") -200/5: -from datetime import datetime - -date_time_str = '2024-03-19 04:19:20' -format = '%Y-%m-%d %H:%M:%S' # Added a space between '%d' and '%H' -date_time_obj = datetime.strptime(date_time_str, format) - -print(date_time_obj) -200/6: type(date_time_str) - 1: %history -g -f history.txt diff --git a/holder.py b/holder.py deleted file mode 100644 index 54ad54ab..00000000 --- a/holder.py +++ /dev/null @@ -1,280 +0,0 @@ -from utils.reader import SigmaWalletReader, PriceReader -from utils.dash_utils import create_pie_chart, create_bar_chart, create_table_component -from dash import Dash, html, dash_table, dcc, callback_context -import dash_bootstrap_components as dbc -import pandas as pd -import plotly.express as px -from dash.dependencies import Input, Output, State -import plotly.graph_objs as go - -from flask_login import LoginManager, UserMixin, login_user -from flask import Flask, request, session, redirect, url_for -from flask_session import Session - -server = Flask(__name__) -server.config['SECRET_KEY'] = 'your_super_secret_key' # Change this to a random secret key -server.config['SESSION_TYPE'] = 'filesystem' # Example: filesystem-based session storage -Session(server) -''' -TODO -- Config for background to allow for customizability down the road -- inital user page for dashboard, then once address entered show the whole dashboard --tx link to be url - cliockable -- mobile friendly with tables -- confetti when block found -- block found indicator -- inital user page visuals -- BLock reward is vairable based on date - reads in df - -INITIAL USER PAGE METRICS: -- TOTAL HASHRATE -- TOTAL MINERS -- ALGO -- Reward -- Pool Fee -- Min Payout -- Difficulty -- Amount Paid -- Place to enter address - -''' - -# Initialize the Dash app -app = Dash(__name__, server=server, url_base_pathname='/', external_stylesheets=[dbc.themes.SUPERHERO]) -server = app.server # Expose the underlying Flask server - - -price_reader = PriceReader() -sigma_reader = SigmaWalletReader(config_path="../conf") - -def update_charts(wallet_address): - wallet = wallet_address - if wallet != 'Enter Your Address': - short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) - else: - short_wallet = wallet - - mining_df, performance_df = sigma_reader.get_mining_stats(wallet) - block_df, miner_df, effort_df = sigma_reader.get_block_stats(wallet) - pool_df, top_miner_df = sigma_reader.get_pool_stats(wallet) - miner_reward_df = sigma_reader.get_estimated_payments(wallet) - miner_performance = sigma_reader.get_miner_samples(wallet) - btc_price, erg_price = price_reader.get(debug=False) - - try: - pool_hash = round(pool_df[pool_df['Pool Stats'] == 'poolHashrate [Gh/s]']['Values'].iloc[0], 5) - network_difficulty = round(pool_df[pool_df['Pool Stats'] == 'networkDifficulty [Peta]']['Values'].iloc[0], 5) - network_hashrate = round(pool_df[pool_df['Pool Stats'] == 'networkHashrate [Th/s]']['Values'].iloc[0], 5) - - except IndexError: - print('POOL API EXCEPTION TRIGGERED!!!!') - pool_hash = -10 - network_difficulty = -10 - network_hashrate = -10 - - your_total_hash = round(performance_df[performance_df['Worker'] == 'Totals']['Hashrate [Mh/s]'].iloc[0], 5) - avg_block_effort = round(effort_df[effort_df['Mining Stats'] == 'Average Block Effort']['Values'].iloc[0], 5) - - # Masking Values we dont need in the tables - mask = performance_df['Worker'] == 'Totals' - mask_performance_df = performance_df[~mask] - - values_to_drop = ['networkHashrate [Th/s]', 'networkDifficulty [Peta]', - 'poolHashrate [Gh/s]', 'networkType', 'connectedPeers', 'rewardType'] - mask = pool_df['Pool Stats'].isin(values_to_drop) - pool_df = pool_df[~mask] - - # Creating Charts - miner_chart = create_pie_chart(miner_df, 'miner', 'Number of Blocks Found') - top_miner_chart = create_pie_chart(top_miner_df, 'miner', 'hashrate') - estimated_reward = create_pie_chart(miner_reward_df, 'miner', 'reward', est_reward=True) - - - effort_chart = create_bar_chart(block_df, x='Time Found', y='effort', - color='networkDifficulty', - labels={'Time Found': 'Block Creation Date', - 'effort': 'Effort', 'networkDifficulty': 'Network Difficulty'}) - print(miner_performance.columns) - - miner_performance_chart = px.line(miner_performance, - x='created', - y='hashrate', - color='worker', - title='Hashrate Over Time', - labels={'hashrate': 'Hashrate', 'created': 'Time'}, - markers=True) - - # Update layout for customization - miner_performance_chart.update_layout( - paper_bgcolor='rgba(0,0,0,0)', - plot_bgcolor='rgba(0,0,0,0)', - legend_title_text='Miner', - legend=dict(font=dict(color='#FFFFFF')), - titlefont=dict(color='#FFFFFF'), - xaxis=dict(title='Time', color='#FFFFFF'), - yaxis=dict(title='Hashrate', color='#FFFFFF') - ) - - # # adding a circle to the effort chart if you found the block - # try: - # my_wallet_blocks = block_df[block_df['my_wallet']] - # except KeyError: - # block_df['my_wallet'] = 'NO WALLET SUBMITTED' - # my_wallet_blocks = block_df[block_df['my_wallet']] - - # block_df = block_df.drop(['my_wallet'], axis=1) # might need to change the name of this df - # effort_chart.add_trace(go.Scatter(x=my_wallet_blocks['Time Found'], y=my_wallet_blocks['effort'], mode='markers', - # marker=dict(color='Red', size=10, symbol='circle'), name='My Wallet')) - - # Network Difficulty Plot - net_diff_plot={'data': [go.Scatter(x=block_df['Time Found'], y=block_df['networkDifficulty'], - mode='lines+markers', name='Network Difficulty', line={'color': '#00CC96'})], - - 'layout': go.Layout(title='Ergo Network Difficulty Over Time', titlefont={'color': '#FFFFFF'}, - paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', - margin={'l': 40, 'b': 40, 't': 50, 'r': 50}, hovermode='closest', - legend={'font': {'color': '#FFFFFF'}}, font=dict(color='#FFFFFF'))} - - # Define the style for the crypto prices - metric_style = { - 'padding': '20px', - 'fontSize': '20px', - 'margin': '10px', - 'border': '1px solid #555', # Adjusted for dark mode - 'borderRadius': '5px', - 'background': '#333', # Dark background - 'color': '#fff', # Light text color - 'boxShadow': '0 2px 4px rgba(255,255,255,.1)', # Subtle white shadow for depth - 'minWidth': '150px', # Ensure blocks don't become too narrow - 'textAlign': 'center' # Center text horizontally - } - - # Create the crypto prices HTML div elements as a row - crypto_prices_row = html.Div([ - html.Div(f"BTC: ${btc_price}", style=metric_style), - html.Div(f"ERG: ${erg_price}", style=metric_style), - html.Div(f"Total Hashrate: {your_total_hash} Mh/s", style=metric_style), - html.Div(f"Pool Hashrate: {pool_hash} Gh/s", style=metric_style), - html.Div(f"Network Hashrate: {network_hashrate} Th/s", style=metric_style), - html.Div(f"Average Block Effort: {avg_block_effort}", style=metric_style), - html.Div(f"Network Difficulty: {network_difficulty} P", style=metric_style), - ], style={'display': 'flex', 'flexDirection': 'row', 'justifyContent': 'center'}) - - if wallet == 'ADDRESS': - dashboard_title = 'Sigma Mining Pool Dashboard - ENTER YOUR ADDRESS' - else: - dashboard_title = 'Sigma Mining Pool Dashboard - {}'.format(short_wallet) - return miner_chart, top_miner_chart, estimated_reward, effort_chart, mining_df, mask_performance_df, pool_df, crypto_prices_row, dashboard_title, block_df, net_diff_plot, miner_performance_chart - -miner_chart, top_miner_chart, estimated_reward, effort_chart, mining_df, mask_performance_df, pool_df, crypto_prices_row, dashboard_title, block_df, net_diff_plot, miner_performance_chart= update_charts('ADDRESS') - -app.layout = html.Div(children=[ - html.H1(id='dashboard-title', children=[]), - - html.Label('Enter your wallet ID:'), - dcc.Input(id='wallet-input', type='text', value=''), - html.Button('Submit', id='submit-btn', n_clicks=0), - html.Div(id='output-container'), - - html.Div(id='crypto-prices', children=[]), - dcc.Interval( - id='interval-component', - interval=60*1000, # in milliseconds, every 1 minutes - n_intervals=0 - ), - - html.Div([html.Div(create_table_component('Payment Stats', 'mining-stats', - mining_df.columns, mining_df, max_table_width='400px'), style={'flex': '1'}), - html.Div(create_table_component('Your Performance Stats', 'performance-stats', - mask_performance_df.columns, mask_performance_df, max_table_width='600px'), style={'flex': '1'}), - html.Div(create_table_component('Pool and Network Stats', 'pool-stats', - pool_df.columns, pool_df, max_table_width='520px'), style={'flex': '1'}),], - style={'display': 'flex'}), - - dcc.Graph(id='miner-performance-plot', figure=miner_performance_chart, style={'backgroundColor': 'rgba(17,17,17,1)'}), - dcc.Graph(id='network-difficulty-plot', figure=net_diff_plot, style={'backgroundColor': 'rgba(17,17,17,1)'}), - - html.Div(children=[html.Div(children=[html.H2('Blocks Found by Miners'), - dcc.Graph(id='miner-blocks', figure=miner_chart),], - style={'flex': 1}), - - html.Div(children=[html.H2('Top Miners by Hashrate Mh/s'), - dcc.Graph(id='top-miner-chart', figure=top_miner_chart)], - style={'flex': 1}), - html.Div(children=[html.H2('Estimated Rewards'), - dcc.Graph(id='estimated-reward', figure=estimated_reward)], - style={'flex': 1}),], - style={'display': 'flex', 'flexDirection': 'row', 'gap': '20px'}), - - html.Div(children=[html.H2('Block Effort Over Time'), - dcc.Graph(id='effort-chart', figure=effort_chart)], - style={'margin-top': '20px'}), - - html.Div(children=[html.H2('Block Statistics'), - dash_table.DataTable(id='block-stats', columns=[{"name": i, "id": i} for i in block_df.columns], - data=block_df.to_dict('records'), style_table={'overflowX': 'auto'}, - style_cell={'height': 'auto', 'minWidth': '180px', - 'width': '180px', 'maxWidth': '180px', - 'whiteSpace': 'normal', 'textAlign': 'left', - 'padding': '10px',}, - style_header={'backgroundColor': 'rgb(30, 30, 30)', 'color': 'white', - 'fontWeight': 'bold', 'textAlign': 'center',}, - style_data={'backgroundColor': 'rgb(50, 50, 50)', 'color': 'white', - 'border': '1px solid black',}, - style_data_conditional=[{'if': {'column_id': 'status', 'filter_query': '{status} eq confirmed'}, - 'backgroundColor': 'lightgreen', 'color': 'black', 'after': {'content': '" ✔"'}}], - style_as_list_view=True, style_cell_conditional=[{'if': {'column_id': c}, - 'textAlign': 'left'} for c in ['Name', 'status']], - style_header_conditional=[{'if': {'column_id': 'status'}, 'textAlign': 'center'}])], - style={'padding': '20px'})], - style={'backgroundColor': 'rgba(17,17,17,1)', 'color': '#FFFFFF', 'padding': '10px'}) - - -@app.callback([ - Output('dashboard-title', 'children'), - Output('miner-blocks', 'figure'), - Output('top-miner-chart', 'figure'), - Output('estimated-reward', 'figure'), - Output('effort-chart', 'figure'), - Output('crypto-prices', 'children'), - Output('mining-stats', 'data'), # Adding Output for the mining-stats DataTable - Output('performance-stats', 'data'), # Adding Output for the performance-stats DataTable - Output('pool-stats', 'data'), # Adding Output for the pool-stats DataTable - Output('block-stats', 'data'), - Output('network-difficulty-plot', 'figure'), - Output('miner-performance-plot', 'figure'), - Input('submit-btn', 'n_clicks'), - State('wallet-input', 'value') -], [Input('interval-component', 'n_intervals')]) - - -@server.route('/set/') -def update_output(n_clicks, wallet_address, n_intervals): - trigger_id = callback_context.triggered[0]['prop_id'].split('.')[0] - print(f"Callback triggered by: {trigger_id}") - - if trigger_id == 'interval-component' or n_clicks > 0: - wallet = wallet_address - print(f'Wallet ID entered: "{wallet_address}"') - else: - wallet = 'Enter Your Address' - - session['wallet_id'] = wallet - miner_chart, top_miner_chart, estimated_reward, effort_chart, mining_df, mask_performance_df, pool_df, crypto_prices_row, dashboard_title, block_df, net_diff_plot, miner_performance_chart = update_charts(wallet) - - # Convert DataFrames to lists of dictionaries for DataTables - mining_stats_data = mining_df.to_dict('records') - performance_stats_data = mask_performance_df.to_dict('records') - pool_stats_data = pool_df.to_dict('records') - block_data = block_df.to_dict('records') - - # Return the new figures and data - return ( - dashboard_title, miner_chart, top_miner_chart, estimated_reward, effort_chart, - crypto_prices_row, - mining_stats_data, performance_stats_data, pool_stats_data, block_data, net_diff_plot, miner_performance_chart - ) - -# Run the app -if __name__ == '__main__': - app.run_server(debug=True, host='0.0.0.0', port=8050) \ No newline at end of file diff --git a/layouts/__pycache__/front_page.cpython-310.pyc b/layouts/__pycache__/front_page.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b0e308d905761592c704b87864ffe1424db3bb2 GIT binary patch literal 11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0r{rHF6u3{gFuSQiXYdNE)185lX3gD?`7V3=be3zB?Iy5&tcDf z19@oHDGvg$Zt6(KkpR1uR0gToVP#cuyEh= zqrmf8P(AzSvj2}=F?e_T-U2bnz6V1MzE1bT(iA`}CSc4LLrNdv_O;>E{QWDAXJJl; z`z{c6tt0mBDY(GCuaOra22I1{l;N|X;#qd|@Kbn@PY(5FV_ z+cCSYDJfwhtg9+==~fX;@_wE@kzDGD^bPK|>b##oS~NkvS-3!nV$r4YLFz?0`xb70 ziY4ee3)3c47xc;Gzbd32ED{KCz{v-XMnr}WfANC!?tWPk{ zawtbnA04X!1VPW`H1nw`6F+?=^9TB`T2E77vrebJZv7+wkZ5IBDh(V-rGk{@5MFWf zcoVk~l3r2W!~2Gm4^1;~v0W>S(90n3;E^6uhbI$SDzzmEe@MOpx)|c>09PP*Gm3<^ z3BMpx4A9q({U9p2Eg!cP^5qZ8#d8X)@%|J1IX9BoKfDPd2TE|V$|-HkyQrWyqBz~z z@;nv2RM5*BiU9_wMgg&8G0{)g2El5nMl4bZ7ngBkxKro9je#PcjPdRwD;Gr~lT`R` zQE#_=>tzdH+{dQ)j|u!~Dqf@F77ZJaH)_aMM)0n1-O_Md{4w=Xs%@Lpk`vq5#@X z9YLC}5BbXr_~N639}L{T;9qf<^?0k6JpV-RQnj7Z`jOtVceM4yw2%*dY8&8NEA=&d O5Z{;aCXQUqeEeTj$lUY* literal 0 HcmV?d00001 diff --git a/layouts/__pycache__/front_page_1.cpython-312.pyc b/layouts/__pycache__/front_page_1.cpython-312.pyc index 36bc303a49086e9c7e39d49f06526627d63a65d4..ff8a06ab1e082d0da45a729e1b20fbc1d75cc129 100644 GIT binary patch delta 58 zcmZqbU~KDPlH#ajcGcR4YAU{7x Mw={FJ0P80^00f^CE&u=k delta 54 zcmZqcU~KAO7*)AReq)_N#&|arSi{z@-LmlDOd7``H@O0hs$eA%J+I^ z4=!a_7)(u1_v`ER^y~M&_XeGj5l6xAtKT`=xPC@a{+SB9e+CNAW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JN6`mPsU zH&rnZ(oVx+{1CBqkdnhlppkU|6MlmTH!1lQO8%IVzoX>eD3P0XopRE=AN&yK>g)(cAm8ce zeVmwx#Fyg&{GCU@+sD8Utv|Ul>{0e{_85B{KF|~JhMr^<+i zvuuu@@ROcm$JlXp0<@Fs#!es9JjtHMnoqH3?ig~EBD}C?*>mhPMm^2W$m>(=ELwc} zP9`qJC3bGzZ06W!)^)sr=i@>$JAx?Zukhc+rY!+Bp8{;YjC|jT+;%jB?`wX8|1}80 zJpBwXb;S~+JD(U4)9Y~lO{y-WF-9n^m;xk@#33$Ri4@P+p?mW+pT#TuEwuN)^sf+B zaz>y_|Ahvyx4>Rv=>HTn{tuKKN76rV@!E@5%kpb2g`&%^$WU~dBCPx=YV{H&67bI< z2TVhQ@>eO5{23>}z0jY<`qq*LGM-AUz`-9;J4v8`4ewJz-U+JY5ZhJ#>DMHRD_>4w zUHR&DL|RG1^FN^u8vifqOml8AAv=>I?N2QPo*Q}P$P4gMvh23Yov!rGY@I zlgG$4`efSvhTIVe{fuNEG6_qO93*kWMxw4;_hy#yA=C5P{CB9YAu`O5y1;1sziC{@ zrC9b$_)Z$h#dAT_YzJ?r5p-^Ro?oM~dHgxr2CGdmXT*a8M603UtQBbxg$G3wA?($_vD;`|fE%IE56F7^g!yg0{(P zrdONn3q|C3k&-b=N|ex>rLPZgy~e35x0YVN+(o{hsz<4M*1K8vDHrG~vHTjSJ*21#1|$OW*rMCe84_rP?t$ zC-W%K;I->Mq6X5^OPf#TUW}#vnf=>J>C1vUk z*+w0Iga{v_VxJ8=tQUCaumUBTM^aQStA|t^3wUHU m(s8;qq9h>=2S>yPa3djy2lu{hDL-kyfD0`N>=aew`~M4S-;_N7 literal 0 HcmV?d00001 diff --git a/layouts/__pycache__/mining_page_1.cpython-310.pyc b/layouts/__pycache__/mining_page_1.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..335888fa68f520c75cc19d73d59c51de91a8c38e GIT binary patch literal 9795 zcmbVSYm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X@~F z9aNKUa7PqB9YmR|Z z43i#ri9;z}W`s;({oCAm=LDBv6!)^Hy9`d~?aPUZp)uW^nu4+Ww>WE@@F#g#~2jF2iA}2 z$q?kY_K~)D%+;(XhhaK@3poN@K~d=;R?VAC-(t(4xtW&)PfJAL2k1-KiUu#EH43{5 zqU0!CDe#il;kN=;+I~i>h6B9ZE5_(6U@vSUuflVMk8U`H`eO*k5l)~^CrjZTl?w@U z2(A`(8e@!%wQ#VZA}7A1=#b7Z#Rz%@u9uFGFJZSg=n61GwS}axNZVt4C@PEXLMP=> zb`oxS%hEqZvl^iZApo|r$Fwo?ptr1^oQBD=zlab&xA81zxQdD?XfA)kGKD4{F?|Eh zmB%}<&Qe-tsYWHzE=V1U*GjQ~s#o}cEUu^{qduOHN($?$l4`A5LIdpqInvR?+Ej@| zPohph7=q7yZRBb^yJ9cN8A9eD!fOa0BYcOj0Hd2K$s%0d^oVV<-nnSv4CMeM=>tppK1oo5v>A80#HhwdRFNX#7@Y@yeOAdC&7~RzDHfI46TX8<%)Bgh zg_{&H6w|t;-@{1#mO>r-XP|dAL0?c(#63~IL!`SIk(fzOZ^3;1&UHAY*G|`?<9!4X z9%?Abl+f%%=t8g}1fjoSlR>-SOK_pVrO#nCevMymxWU2r!+)fSOr#p3e3*R@=s1iu zy2%aryzx!;-Q2fzmt_%iUdeZTM>IlcWxuex9Vlfd47Owq)YIy%WCi2mb|d CRMU6> diff --git a/layouts/front_page.py b/layouts/front_page.py index be6c1428..5a1370f2 100644 --- a/layouts/front_page.py +++ b/layouts/front_page.py @@ -1,7 +1,7 @@ import dash from dash import html, dcc, Input, Output, dash_table import dash_bootstrap_components as dbc -from utils.reader import SigmaWalletReader, PriceReader +from utils.api_reader import SigmaWalletReader, PriceReader from pandas import DataFrame from utils.dash_utils import metric_row_style, image_style, create_row_card, card_style, image_card_style, bottom_row_style, bottom_image_style, card_color, large_text_color, small_text_color, background_color import plotly.graph_objs as go @@ -20,30 +20,25 @@ def create_image_text_block(image, text, value): return html.Div(style=bottom_row_style, children=[ html.Img(src='assets/{}'.format(image), style=bottom_image_style), - html.Span(text, style={'padding': '10px', 'width': '100%', 'height': 'auto', 'color': 'white'}), - html.Span(value, style={'color': large_text_color})]) + html.Span(text, style={'padding': '5px', 'color': 'white'}), + html.Span(value, style={'padding': '5px', 'color': large_text_color})]) # Style for the card containers card_style = { 'backgroundColor': card_color, 'color': small_text_color, - # 'marginBottom': '25px', 'padding': '25px', 'justifyContent': 'center', - # 'border': '1px solid {}'.format(large_text_color), } top_card_style = { 'backgroundColor': card_color, 'color': small_text_color, - # 'margin': '10px', 'height': '225px', 'padding': '15px', 'justifyContent': 'center', 'textAlign': 'center', - 'justify': 'center', - # 'border': '1px solid {}'.format(large_text_color), - + 'justify': 'center', } top_image_style = { @@ -83,16 +78,17 @@ def create_row_card(image, h2_text, p_text): html.P(p_text)]), style={'marginRight': 'auto', 'marginLeft': 'auto'}, width=4,) def setup_front_page_callbacks(app, reader): + reader.update_data() - @app.callback([Output('metric-1', 'children'), - Output('metric-2', 'children'),], - [Input('fp-int-1', 'n_intervals')]) - - def update_metrics(n): - print('UPDATING FRONT PAGE') + @app.callback([Output('metric-1', 'children')], + [Input('fp-int-4', 'n_intervals')]) - data = reader.get_front_page_data() # - _, ergo = price_reader.get(debug=debug) + def update_first_row(n): + reader.update_data() + data = reader.data + # data = reader.get_front_page_data() # + # _, ergo = price_reader.get(debug=debug) + ergo = reader.erg_price # payout_schema = 'Schema: {}'.format(data['payoutScheme']) n_miners = '{}'.format(data['connectedMiners']) hashrate = '{} GH/s'.format(round(data['poolHashrate'], 3)) @@ -101,16 +97,27 @@ def update_metrics(n): children=[create_row_card('assets/boltz.png', hashrate, 'Pool Hashrate'), create_row_card('assets/smileys.png', n_miners, 'Miners Online'), create_row_card('assets/coins.png', ergo, 'Price ($)')]) + return [row_1] + + + @app.callback([ + Output('metric-2', 'children'),], + [Input('fp-int-1', 'n_intervals')]) + + def update_metrics(n): + # reader.update_data() + data = reader.data + md = 4 row_2 = dbc.Row(children=[ - dbc.Col(md=md, children=[ + dbc.Col(md=md, style={'padding': '10px'}, children=[ dbc.Card(style=bottom_row_style, children=[ create_image_text_block('min-payout.png', 'Minimum Payout:', data['minimumPayment']), create_image_text_block('percentage.png', 'Pool Fee:', '{}%'.format(data['fee'])), create_image_text_block('ergo.png', 'Total Paid:', '{} ERG'.format(round(data['paid'], 3))), ]) ]), - dbc.Col(md=md, children=[ + dbc.Col(md=md, style={'padding': '10px'}, children=[ dbc.Card(style=bottom_row_style, children=[ create_image_text_block('bolt.png', 'Network Hashrate:', '{} TH/s'.format(round(data['networkHashrate'], 3))), create_image_text_block('gauge.png', 'Network Difficulty:', '{}P'.format(round(data['networkDifficulty'], 3))), @@ -118,33 +125,33 @@ def update_metrics(n): ]) ]), - dbc.Col(md=md, children=[ + dbc.Col(md=md, style={'padding': '10px'}, children=[ dbc.Card(style=bottom_row_style, children=[ create_image_text_block('triangle.png', 'Schema:', data['payoutScheme']), create_image_text_block('ergo.png', 'Blocks Found:', data['blocks']), - create_image_text_block('ergo.png', 'Current Block Effort:', round(data['pool_effort'], 3)), + create_image_text_block('ergo.png', 'Current Block Effort:', round(data['poolEffort'], 3)), ]) ])]) - return row_1, row_2 - + return [row_2] + @app.callback([Output('plot-1', 'figure'),Output('plot-title', 'children'),], [Input('fp-int-2', 'n_intervals'), Input('chart-dropdown', 'value')]) def update_plots(n, value): if value == 'effort': - block_df = reader.get_block_stats('') # + block_df = reader.block_df title = 'EFFORT AND DIFFICULTY' block_df = block_df.sort_values('Time Found') - block_df['Rolling Effort'] = block_df['effort'].expanding().mean() + block_df['effort'] = block_df['effort'] * 100 + # block_df['Rolling Effort'] = block_df['effort'].expanding().mean() response_df = block_df.melt(id_vars = ['Time Found'], value_vars=['Rolling Effort', 'effort', 'networkDifficulty']) effort_response_chart = px.line(response_df[response_df['variable'] != 'networkDifficulty'], x='Time Found', y='value', color='variable', - color_discrete_map=color_discrete_map, markers=True) # Add 'networkDifficulty' on a secondary y-axis @@ -162,20 +169,22 @@ def update_plots(n, value): legend_title_text='Metric', legend=dict(font=dict(color='#FFFFFF')), titlefont=dict(color='#FFFFFF'), - xaxis=dict(title='Block Found Time', color='#FFFFFF',showgrid=False, showline=False, zeroline=False), - yaxis=dict(title='Effort', color='#FFFFFF'), - yaxis2=dict(title='Network Difficulty', color='#FFFFFF', overlaying='y', side='right'), + xaxis=dict(title='Time Found', color='#FFFFFF',showgrid=False, showline=False), + yaxis=dict(title='Effort [%]', color='#FFFFFF', side='right'), + yaxis2=dict(title='Network Difficulty', color='#FFFFFF', overlaying='y'), ) + return effort_response_chart, title title = 'HASHRATE OVER TIME' - total_hashrate_df = reader.get_total_hash() + total_hashrate_df = reader.get_total_hash_data() total_hashrate_df = total_hashrate_df.sort_values(['Date']) + total_hashrate_df['Hashrate'] = total_hashrate_df['Hashrate'] total_hashrate_plot={'data': [go.Scatter(x=total_hashrate_df['Date'], y=total_hashrate_df['Hashrate'], mode='lines+markers', name='Hashrate Over Time', line={'color': small_text_color})], - 'layout': go.Layout(xaxis = {'showgrid': False},yaxis = {'showgrid': True}, + 'layout': go.Layout(xaxis = {'showgrid': False, 'title': 'Snap Shot Time'},yaxis = {'showgrid': True, 'title': 'GH/s'}, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', margin={'l': 40, 'b': 40, 't': 50, 'r': 50}, hovermode='closest', legend={'font': {'color': '#FFFFFF'}}, font=dict(color=small_text_color))} @@ -191,43 +200,18 @@ def update_plots(n, value): Input('dataset-dropdown', 'value')]) def update_content(n, selected_data): - block_df= reader.get_block_stats('') - latest = max(block_df['Time Found']) - + block_df= reader.block_df if selected_data == 'blocks': - - # print(block_df.columns) block_df['Confirmation'] = round(block_df['confirmationProgress'], 2) - block_df = block_df.filter(['Time Found', 'blockHeight', 'miner', 'effort', 'reward', 'status', 'Confirmation']) + + block_df = block_df.filter(['Time Found', 'blockHeight', 'miner', 'effort [%]', 'reward [erg]', 'Confirmation [%]']) df = block_df + df['miner'] = df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) title = 'Blocks Data' elif selected_data == 'miners': - data = reader.get_front_page_data() # - top_miner_df = reader.get_all_miner_data('') - ls = [] - print(latest) - for miner in top_miner_df.miner.unique(): - temp = top_miner_df[top_miner_df.miner == miner] - temp_block = block_df[block_df.miner == miner] - print('\--------', temp_block['Time Found'], miner, 'minerszzzz') - try: - temp_latest = max(temp_block['Time Found']) - print('latest') - except ValueError: - temp_latest = min(block_df['Time Found']) - - if not isinstance(latest, str): - temp_latest = min(block_df['Time Found']) - - - temp_hash = round(temp.hashrate.sum(), 3) - effort = reader.calculate_mining_effort(data['networkDifficulty'], data['networkHashrate'], temp_hash, temp_latest) - ttf = reader.calculate_time_to_find_block(data['networkDifficulty'], data['networkHashrate'], temp_hash, temp_latest) - ls.append([miner, temp_hash, round(temp.sharesPerSecond.sum(), 2), effort, ttf]) - - df = DataFrame(ls, columns=['Miner', 'Hashrate', 'SharesPerSecond', 'Effort', 'Time To Find']) - + df = reader.get_latest_worker_samples(totals=True) + df = df.rename(columns={"Effort": "Current Effort [%]", "Hashrate": "MH/s", 'TTF': 'TTF [Days]'}) title = 'Current Top Miners' else: @@ -246,6 +230,7 @@ def get_layout(reader): dcc.Interval(id='fp-int-1', interval=60*1000, n_intervals=0), dcc.Interval(id='fp-int-2', interval=60*1000, n_intervals=0), dcc.Interval(id='fp-int-3', interval=60*1000, n_intervals=0), + dcc.Interval(id='fp-int-4', interval=60*1000, n_intervals=0), html.H1('ERGO Sigmanaut Mining Pool', style={'color': large_text_color, 'textAlign': 'center',}), # Metrics overview row diff --git a/layouts/front_page_1.py b/layouts/front_page_1.py deleted file mode 100644 index 96b77520..00000000 --- a/layouts/front_page_1.py +++ /dev/null @@ -1,400 +0,0 @@ -import dash -from dash import html, dcc, Input, Output, dash_table -import dash_bootstrap_components as dbc -from utils.api_reader import SigmaWalletReader, PriceReader -from pandas import DataFrame -from utils.dash_utils import metric_row_style, image_style, create_row_card, card_style, image_card_style, bottom_row_style, bottom_image_style, card_color, large_text_color, small_text_color, background_color -import plotly.graph_objs as go -import plotly.express as px - -from dash import html -price_reader = PriceReader() -# sigma_reader = SigmaWalletReader(config_path="../conf") - -debug = False - -button_color = large_text_color - - -# refactor this into dash_utils -def create_image_text_block(image, text, value): - return html.Div(style=bottom_row_style, children=[ - html.Img(src='assets/{}'.format(image), style=bottom_image_style), - html.Span(text, style={'padding': '5px', 'color': 'white'}), - html.Span(value, style={'padding': '5px', 'color': large_text_color})]) - -# Style for the card containers -card_style = { - 'backgroundColor': card_color, - 'color': small_text_color, - 'padding': '25px', - 'justifyContent': 'center', -} - -top_card_style = { - 'backgroundColor': card_color, - 'color': small_text_color, - 'height': '225px', - 'padding': '15px', - 'justifyContent': 'center', - 'textAlign': 'center', - 'justify': 'center', -} - -top_image_style = { - 'width': '120px', - 'display': 'block', # Use block display style - 'margin-left': 'auto', # Auto margins for horizontal centering - 'margin-right': 'auto', - 'margin-top': 'auto', # Auto margins for vertical centering (if container allows) - 'margin-bottom': 'auto', - 'max-width': '100%', # Ensures the image is responsive and does not overflow its container - 'height': 'auto', # Keeps image aspect ratio - 'padding': '10px'} - -# Style for the metric rows inside the cards -metric_row_style = { - 'display': 'flex', - 'alignItems': 'center', - 'justifyContent': 'flex-start', - 'fontSize': '13px', -} - -color_discrete_map = { - 'Rolling Effort': 'black', - 'effort': 'white', - 'networkDifficulty': large_text_color -} - -table_style = {'backgroundColor': card_color, 'color': large_text_color, - 'fontWeight': 'bold', 'textAlign': 'center', 'border': '1px solid black',} - -image_style = {'height': '24px'} - -def create_row_card(image, h2_text, p_text): - return dbc.Col(dbc.Card(style=top_card_style, children=[ - dbc.CardImg(src=image, top=True, style=top_image_style), - html.H2(h2_text, style={'color': large_text_color}), - html.P(p_text)]), style={'marginRight': 'auto', 'marginLeft': 'auto'}, width=4,) - -def setup_front_page_callbacks(app, reader): - reader.update_data() - - @app.callback([Output('metric-1', 'children')], - [Input('fp-int-4', 'n_intervals')]) - - def update_first_row(n): - reader.update_data() - data = reader.data - # data = reader.get_front_page_data() # - # _, ergo = price_reader.get(debug=debug) - ergo = reader.erg_price - # payout_schema = 'Schema: {}'.format(data['payoutScheme']) - n_miners = '{}'.format(data['connectedMiners']) - hashrate = '{} GH/s'.format(round(data['poolHashrate'], 3)) - - row_1 = dbc.Row(justify='center', align='stretch', - children=[create_row_card('assets/boltz.png', hashrate, 'Pool Hashrate'), - create_row_card('assets/smileys.png', n_miners, 'Miners Online'), - create_row_card('assets/coins.png', ergo, 'Price ($)')]) - return [row_1] - - - @app.callback([ - Output('metric-2', 'children'),], - [Input('fp-int-1', 'n_intervals')]) - - def update_metrics(n): - # reader.update_data() - data = reader.data - - md = 4 - row_2 = dbc.Row(children=[ - dbc.Col(md=md, style={'padding': '10px'}, children=[ - dbc.Card(style=bottom_row_style, children=[ - create_image_text_block('min-payout.png', 'Minimum Payout:', data['minimumPayment']), - create_image_text_block('percentage.png', 'Pool Fee:', '{}%'.format(data['fee'])), - create_image_text_block('ergo.png', 'Total Paid:', '{} ERG'.format(round(data['paid'], 3))), - ]) - ]), - dbc.Col(md=md, style={'padding': '10px'}, children=[ - dbc.Card(style=bottom_row_style, children=[ - create_image_text_block('bolt.png', 'Network Hashrate:', '{} TH/s'.format(round(data['networkHashrate'], 3))), - create_image_text_block('gauge.png', 'Network Difficulty:', '{}P'.format(round(data['networkDifficulty'], 3))), - create_image_text_block('height.png', 'Block Height:', data['blockHeight']), - ]) - ]), - - dbc.Col(md=md, style={'padding': '10px'}, children=[ - dbc.Card(style=bottom_row_style, children=[ - create_image_text_block('triangle.png', 'Schema:', data['payoutScheme']), - create_image_text_block('ergo.png', 'Blocks Found:', data['blocks']), - create_image_text_block('ergo.png', 'Current Block Effort:', round(data['poolEffort'], 3)), - ]) - ])]) - return [row_2] - - @app.callback([Output('plot-1', 'figure'),Output('plot-title', 'children'),], - [Input('fp-int-2', 'n_intervals'), Input('chart-dropdown', 'value')]) - - def update_plots(n, value): - - if value == 'effort': - block_df = reader.block_df - title = 'EFFORT AND DIFFICULTY' - - block_df = block_df.sort_values('Time Found') - # block_df['Rolling Effort'] = block_df['effort'].expanding().mean() - response_df = block_df.melt(id_vars = ['Time Found'], value_vars=['Rolling Effort', 'effort', 'networkDifficulty']) - - effort_response_chart = px.line(response_df[response_df['variable'] != 'networkDifficulty'], - x='Time Found', - y='value', - color='variable', - markers=True) - - # Add 'networkDifficulty' on a secondary y-axis - effort_response_chart.add_trace(go.Scatter(x=response_df['Time Found'][response_df['variable'] == 'networkDifficulty'], - y=response_df['value'][response_df['variable'] == 'networkDifficulty'], - name='networkDifficulty', - yaxis='y2', - marker=dict(color='rgba(255,0,0,0.5)'), # Adjust color accordingly - mode='lines+markers')) - - # Update layout with secondary y-axis - effort_response_chart.update_layout( - paper_bgcolor='rgba(0,0,0,0)', - plot_bgcolor='rgba(0,0,0,0)', - legend_title_text='Metric', - legend=dict(font=dict(color='#FFFFFF')), - titlefont=dict(color='#FFFFFF'), - xaxis=dict(title='Time Found', color='#FFFFFF',showgrid=False, showline=False), - yaxis=dict(title='Effort [%]', color='#FFFFFF', side='right'), - yaxis2=dict(title='Network Difficulty', color='#FFFFFF', overlaying='y'), - ) - - return effort_response_chart, title - - title = 'HASHRATE OVER TIME' - total_hashrate_df = reader.get_total_hash_data() - total_hashrate_df = total_hashrate_df.sort_values(['Date']) - total_hashrate_df['Hashrate'] = total_hashrate_df['Hashrate'] - - total_hashrate_plot={'data': [go.Scatter(x=total_hashrate_df['Date'], y=total_hashrate_df['Hashrate'], - mode='lines+markers', name='Hashrate Over Time', line={'color': small_text_color})], - - 'layout': go.Layout(xaxis = {'showgrid': False, 'title': 'Snap Shot Time'},yaxis = {'showgrid': True, 'title': 'GH/s'}, - paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', - margin={'l': 40, 'b': 40, 't': 50, 'r': 50}, hovermode='closest', - legend={'font': {'color': '#FFFFFF'}}, font=dict(color=small_text_color))} - - return total_hashrate_plot, title - - - @app.callback([ - Output('table', 'data'), - Output('dropdown-title', 'children'), - ], - [Input('fp-int-3', 'n_intervals'), - Input('dataset-dropdown', 'value')]) - - def update_content(n, selected_data): - block_df= reader.block_df - if selected_data == 'blocks': - block_df['Confirmation'] = round(block_df['confirmationProgress'], 2) - - block_df = block_df.filter(['Time Found', 'blockHeight', 'miner', 'effort [%]', 'reward [erg]', 'Confirmation [%]']) - - df = block_df - df['miner'] = df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - title = 'Blocks Data' - elif selected_data == 'miners': - df = reader.get_latest_worker_samples(totals=True) - df = df.rename(columns={"Effort": "Current Effort [%]", "Hashrate": "MH/s", 'TTF': 'TTF [Days]'}) - title = 'Current Top Miners' - - else: - df = DataFrame() # Empty dataframe as a fallback - title = 'Please select an option' - - columns = [{"name": i, "id": i} for i in df.columns] - table_data = df.to_dict('records') - - return table_data, title - - -def get_layout(reader): - return html.Div([dbc.Container(fluid=True, style={'backgroundColor': background_color, 'padding': '10px', 'justifyContent': 'center', 'fontFamily': 'sans-serif', 'color': '#FFFFFF', 'maxWidth': '960px' }, - children=[ - dcc.Interval(id='fp-int-1', interval=60*1000, n_intervals=0), - dcc.Interval(id='fp-int-2', interval=60*1000, n_intervals=0), - dcc.Interval(id='fp-int-3', interval=60*1000, n_intervals=0), - dcc.Interval(id='fp-int-4', interval=60*1000, n_intervals=0), - - html.H1('ERGO Sigmanaut Mining Pool', style={'color': large_text_color, 'textAlign': 'center',}), - # Metrics overview row - dbc.Row(id='metric-1', justify='center', style={'padding': '5px'}), - - # Detailed stats - dbc.Row(id='metric-2', justify='center', style={'padding': '5px'}), - - # Mining Address Input - dbc.Row(justify='center', children=[ - dbc.Col(md=8, children=[ - dcc.Input(id='mining-address-input', type='text', placeholder='Mining Address', style={ - 'width': '100%', - 'padding': '10px', - 'marginTop': '20px', - 'borderRadius': '5px' - }), - ]) - ]), - - # Start Mining Button - dbc.Row(justify='center', children=[ - html.Button('Start Mining ⛏️', id='start-mining-button', style={ - 'marginTop': '20px', - 'backgroundColor': button_color, - 'border': 'none', - 'padding': '10px 20px', - 'color': 'white', - 'fontSize': '20px', - 'borderRadius': '5px', - 'marginBottom': '50px', - 'width': '97.5%', - }) - ]), - - html.Div( - [ - html.Div( - html.H1( - id='plot-title', - children='Please select an option', - style={'fontSize': '24px'} - ), - style={'flex': '1'} - ), - html.Div( - dcc.Dropdown( - id='chart-dropdown', - options=[ - {'label': 'Hashrate', 'value': 'hash'}, - {'label': 'Effort', 'value': 'effort'} - ], - value='hash', # Default value - style={'width': '300px', 'color': 'black'} - ), - style={'flex': '1'} - ) - ], - style={ - 'display': 'flex', - 'justifyContent': 'space-between', - 'alignItems': 'center', - 'padding': '10px' - } - ), - dcc.Graph(id='plot-1', style={'backgroundColor': card_color}), - - html.Div( - [ - html.Div( - html.H1( - id='dropdown-title', - children='Please select an option', - style={'fontSize': '24px'} - ), - style={'flex': '1'} - ), - html.Div( - dcc.Dropdown( - id='dataset-dropdown', - options=[ - {'label': 'Block-Stats', 'value': 'blocks'}, - {'label': 'Top-Miners', 'value': 'miners'} - ], - value='blocks', # Default value - style={'width': '300px', 'color': 'black'} - ), - style={'flex': '1'} - ) - ], - style={ - 'display': 'flex', - 'justifyContent': 'space-between', - 'alignItems': 'center', - 'padding': '10px' - } - ), - - - dash_table.DataTable(id='table', - style_table={'overflowX': 'auto'}, - style_cell={'height': 'auto', 'minWidth': '180px', - 'width': '180px', 'maxWidth': '180px', - 'whiteSpace': 'normal', 'textAlign': 'left', - 'padding': '10px',}, - style_header=table_style, - style_data=table_style,), - - - html.H1('CONNECTING TO THE POOL', - style={'color': 'white', 'textAlign': 'center', 'padding': '10px',}), - - # Column for the markdown - html.Div(children=[ - dcc.Markdown(''' - ## Choose A Port - Based on your hashrate and TLS specificity choose the port that is right for you. - - - Port 3052 - Lower than 10GH/s - No TLS - - Port 3053 - Higher than 10GH/s - No TLS - - Port 3054 - Lower than 10GH/s - TLS - - Port 3055 - Higher than 10GH/s - TLS - - ### Connecting to the Pool - The pools url is 15.204.211.130 - - So if you want TLS and under 10GH/s the port you would choose is 3054 and so on - - #### HIVEOS - 1. Set "Pool URL" to 15.204.211.130:3054 - - #### MMPOS - 1. Modify an existing or create a new pool in Management - 2. In Hostname enter the URL: 15.204.211.130 - 3. Port: 3054 - - #### Linux or Windows - 1. Edit the .sh file for the specific miner, in this case lolminer - 2. In the pool argument enter the full url with port of choice - ``` - POOL=15.204.211.130:3054 - WALLET=.QX-Fan-Club - ./lolMiner --algo AUTOLYKOS2 --pool $POOL --user $WALLET $@ - while [ $? -eq 42 ]; do - sleep 10s - ./lolMiner --algo AUTOLYKOS2 --pool $POOL --user $WALLET $@ - done - ``` - - ## Updating the Dashboard from git - ``` - docker compose pull # pulls the latest docker image - docker compose up -d # Runs the UI - docker compose down # Stops the UI - ``` - - Shout out to Vipor.Net for the dashboard inspiration! - ''') - ], - style={'backgroundColor': background_color, 'color': 'white', 'padding': '20px', 'code': {'color': card_color}})])], - style={'backgroundColor': card_color} # This sets the background color for the whole page -) - -if __name__ == '__main__': - app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) - app.layout = get_layout() - setup_front_page_callbacks(app) - app.run_server(debug=True) diff --git a/layouts/mining_page.py b/layouts/mining_page.py index 4cc87f9b..42259eae 100644 --- a/layouts/mining_page.py +++ b/layouts/mining_page.py @@ -1,5 +1,5 @@ -from utils.reader import SigmaWalletReader, PriceReader -from utils.dash_utils import image_style, create_pie_chart, create_bar_chart, create_table_component, create_row_card, create_image_text_block, card_style, image_card_style, bottom_row_style, card_color, background_color, large_text_color, small_text_color, bottom_image_style, top_row_style +from utils.api_reader import SigmaWalletReader, PriceReader +from utils.dash_utils import image_style, create_pie_chart, create_bar_chart, create_table_component, create_row_card, create_image_text_block, card_style, image_card_style, bottom_row_style, card_color, background_color, large_text_color, small_text_color, bottom_image_style, top_row_style, table_style from dash import Dash, html, dash_table, dcc, callback_context from dash.exceptions import PreventUpdate from urllib.parse import unquote @@ -30,72 +30,41 @@ } def setup_mining_page_callbacks(app, reader): - def get_net_stats(wallet): - pool_df, _ = reader.get_pool_stats(wallet) - try: - pool_hash = round(pool_df[pool_df['Pool Stats'] == 'poolHashrate [Gh/s]']['Values'].iloc[0], 2) - network_difficulty = round(pool_df[pool_df['Pool Stats'] == 'networkDifficulty [Peta]']['Values'].iloc[0], 2) - network_hashrate = round(pool_df[pool_df['Pool Stats'] == 'networkHashrate [Th/s]']['Values'].iloc[0], 2) - - except IndexError: - print('POOL API EXCEPTION TRIGGERED!!!!') - pool_hash = -10 - network_difficulty = -10 - network_hashrate = -10 - return pool_hash, network_difficulty, network_hashrate - - @app.callback([Output('mp-stats', 'children'), - Output('mp-metrics', 'children'),], - [Input('mp-interveral-1', 'n')], + @app.callback([Output('mp-stats', 'children'),], + [Input('mp-interval-4', 'n')], [State('url', 'pathname')]) - def update(n, pathname): + def update_front_row(n, pathname): + wallet = unquote(pathname.lstrip('/')) if wallet != 'Enter Your Address': short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) else: short_wallet = wallet - - mining_df, performance_df = reader.get_mining_stats(wallet) - pool_df, _ = reader.get_pool_stats(wallet) - _, erg_price = price_reader.get(debug=debug) - block_df = reader.get_block_stats(wallet) - last_block_timestamp = max(block_df['Time Found']) - my_blocks = block_df[block_df.my_wallet == True] - try: - my_last_block_timestamp = max(my_blocks['Time Found']) - except ValueError: - my_last_block_timestamp = min(block_df['Time Found']) - - pool_hash, network_difficulty, network_hashrate = get_net_stats(wallet) - - your_total_hash = round(performance_df[performance_df['Worker'] == 'Totals']['Hashrate [Mh/s]'].iloc[0], 2) + worker_df = reader.get_latest_worker_samples(True) + my_worker_df = worker_df[worker_df.Miner == short_wallet] + my_total_hash = round(list(my_worker_df.Hashrate)[0], ) + my_effort = list(my_worker_df.Effort)[0] + my_ttf = list(my_worker_df.TTF)[0] - current_effort = reader.calculate_mining_effort(network_difficulty, network_hashrate, pool_hash * 1e3, last_block_timestamp) - pool_ttf = reader.calculate_time_to_find_block(network_difficulty, network_hashrate, pool_hash * 1e3, last_block_timestamp) - - pool_effort_text = '{}%'.format(current_effort) - pool_ttf_text = '{} Days'.format(pool_ttf) - pool_hash_text = '{} GH/s'.format(pool_hash) + block_df = reader.block_df + block_df['miner'] = block_df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) + block_df['my_wallet'] = block_df['miner'].apply(lambda address: address == wallet) + my_blocks = block_df[block_df.my_wallet == True] - your_effort = reader.calculate_mining_effort(network_difficulty, network_hashrate, your_total_hash, my_last_block_timestamp) - your_ttf = reader.calculate_time_to_find_block(network_difficulty, network_hashrate, your_total_hash, my_last_block_timestamp) - - your_effort_text = '{}%'.format(your_effort) - your_ttf_text = '{} Days'.format(your_ttf) - your_hash_text = '{} MH/s'.format(your_total_hash) - - # Masking Values we dont need in the tables - mask = performance_df['Worker'] == 'Totals' - mask_performance_df = performance_df[~mask] + + ### GATHERING POOL AND YOUR HASH TTF AND EFFORT ### + pool_effort_text = '{}%'.format(reader.data['poolEffort']) + pool_ttf_text = '{} Days'.format(reader.data['poolTTF']) + pool_hash_text = '{} GH/s'.format(reader.data['poolHashrate']) - values_to_drop = ['networkHashrate [Th/s]', 'networkDifficulty [Peta]', - 'poolHashrate [Gh/s]', 'networkType', 'connectedPeers', 'rewardType'] - mask = pool_df['Pool Stats'].isin(values_to_drop) - pool_df = pool_df[~mask] + your_effort_text = '{}%'.format(my_effort) + your_ttf_text = '{} Days'.format(my_ttf) + your_hash_text = '{} MH/s'.format(my_total_hash) + ### CARDS FOR THE ABOVE METRICS pool_stats = dbc.Col(dbc.Card(style=top_row_style, children=[ # html.Img(src=image, style=top_image_style), html.H2('Pool Stats', style={'color': large_text_color, 'textAlign': 'center'}), @@ -113,113 +82,91 @@ def update(n, pathname): dbc.Col([html.H4('TTF', style={'color': large_text_color}), html.P(your_ttf_text),]), dbc.Col([html.H4('Effort', style={'color': large_text_color}), html.P(your_effort_text)])]),]), style={'marginRight': 'auto', 'marginLeft': 'auto'}) - + + ### GATHER THE NEXT STATS FOR PAYMENT ### stats = dbc.Row(justify='center', children=[pool_stats, your_stats]) + return [stats] + + @app.callback([ Output('s1', 'children'), Output('s2', 'children'),], + [Input('mp-interval-1', 'n')], + [State('url', 'pathname')]) + + def update_middle(n, pathname): + wallet = unquote(pathname.lstrip('/')) + + ### PAYMENT STATS ### + my_payment = reader.get_miner_payment_stats(wallet) + + payment_images ={ + 'Pending Shares': 'min-payout.png', + 'Pending Balance': 'triangle.png', + 'Total Paid': 'ergo.png', + 'Last Payment': 'coins.png', + 'Price': 'ergo.png', + 'Schema': 'ergo.png', + } - payment = dict(zip(mining_df['Mining Stats'], mining_df['Values'])) + payment_children = [create_image_text_block(text='{}: {}'.format(key, my_payment[key]), image=payment_images[key]) for key in payment_images.keys() if key != 'lastPaymentLink'] + - payment['Pending Shares'] = round(payment.pop('pendingShares'), 3) - payment['Pending Balance'] = round(payment.pop('pendingBalance'), 3) - payment['Total Paid'] = round(payment.pop('totalPaid'), 3) - payment['Paid Today'] = payment.pop('todayPaid') - payment['Last Payment'] = payment.pop('lastPayment')[:-17] - payment['Price'] = erg_price + return payment_children[:3], payment_children[3:] + + @app.callback([ + + Output('s3', 'children'),], + [Input('mp-interval-1', 'n')], + [State('url', 'pathname')]) + + def update_outside(n, pathname): + wallet = unquote(pathname.lstrip('/')) + ### PAYMENT STATS ### + my_payment = reader.get_miner_payment_stats(wallet) + all_payment_stats = [reader.get_miner_payment_stats(wallet) for wallet in reader.get_miner_ls()] miners = reader.get_miner_ls() ls = [] for miner in miners: - df, _ = reader.get_mining_stats(miner) - shares = df[df['Mining Stats'] == 'pendingShares'].Values[0] + d = reader.get_miner_payment_stats(miner) + shares = d['Pending Shares'] ls.append([miner, shares]) df = pd.DataFrame(ls, columns=['Miner', 'Shares']) total = df.Shares.sum() df['participation'] = [shares / total for shares in df.Shares] - df['reward'] = df['participation'] * 30 + df['reward'] = df['participation'] * reader.block_reward my_df = df[df.Miner == wallet] participation = round(my_df['participation'].values[0] * 100, 3) - print(participation) - - payment['Participation [%]']= participation - payment['Schema'] = 'PPLNS' + my_payment['Participation [%]']= participation - payment_images ={'Pending Shares': 'min-payout.png', - 'Pending Balance': 'triangle.png', - 'Total Paid': 'ergo.png', + payment_images ={'Participation [%]': 'smileys.png', 'Paid Today': 'ergo.png', - 'Last Payment': 'coins.png', - 'Participation [%]': 'smileys.png', - 'Price': 'ergo.png', - 'Schema': 'ergo.png', 'lastPaymentLink': 'ergo.png', } - payment_children = [create_image_text_block(text='{}: {}'.format(key, payment[key]), image=payment_images[key]) for key in payment.keys() if key != 'lastPaymentLink'] + payment_children = [create_image_text_block(text='{}: {}'.format(key, my_payment[key]), image=payment_images[key]) for key in payment_images.keys() if key != 'lastPaymentLink'] link = html.Div(style=bottom_row_style, children=[ html.Img(src='assets/{}'.format('ergo.png'), style=bottom_image_style), - html.Span(dcc.Link('Last Payment Link', href=payment['lastPaymentLink'], target='_blank'), style={'padding': '10px'})]) + html.Span(dcc.Link('Last Payment Link', href=my_payment['lastPaymentLink'], target='_blank'), style={'padding': '10px'})]) payment_children.append(link) - performance = dict(zip(mask_performance_df['Worker'], mask_performance_df['Hashrate [Mh/s]'])) - performance_images = {key: 'qx-fan-club.png' for key in performance.keys()} - performance_children = [create_image_text_block(text='{}: {}'.format(key, performance[key]), image=performance_images[key]) for key in performance.keys()] - performance_children.insert(0, html.H3('Performance Stats', style={'color': '#FFA500', 'fontWeight': 'bold'})) - - pool = dict(zip(pool_df['Pool Stats'], pool_df['Values'])) - pool_images ={'connectedMiners': 'mining_temp.png', - 'sharesPerSecond': 'mining_temp.png', - 'lastNetworkBlockTime': 'mining_temp.png', - 'blockHeight': 'mining_temp.png'} - pool_children = [create_image_text_block(text='{}: {}'.format(key, pool[key]), image=pool_images[key]) for key in pool.keys()] - pool_children.insert(0, html.H3('Pool Stats', style={'color': '#FFA500', 'fontWeight': 'bold'})) - md = 4 - - metrics = dbc.Row(children=[ - dbc.Col(md=md, children=[ - dbc.Card(style=bottom_row_style, children=payment_children[:3]) - ]), - dbc.Col(md=md, children=[ - dbc.Card(style=bottom_row_style, children=payment_children[3:6]) - ]), - - dbc.Col(md=md, children=[ - dbc.Card(style=bottom_row_style, children=payment_children[6:]) - ])]) - - return stats, metrics - - @app.callback([ - Output('chart', 'figure'), - Output('table-2', 'data'), - Output('table-title', 'children'), - ], - [Input('mp-interveral-2', 'n_intervals'), Input('table-dropdown', 'value')], + return [payment_children] + + @app.callback([Output('chart', 'figure'),], + [Input('mp-interval-2', 'n_intervals')], [State('url', 'pathname')]) - def update_charts(n_intervals, table, pathname): - print('updating mining page') + def update_charts(n_intervals, pathname): wallet = unquote(pathname.lstrip('/')) - print(wallet) - pool_hash, network_difficulty, network_hashrate = get_net_stats(wallet) - if wallet != 'Enter Your Address': - short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) - else: - short_wallet = wallet - - print(wallet, 'wallllllllet') - block_df = reader.get_block_stats(wallet) # - miner_performance = reader.get_miner_samples(wallet) # - last_block_timestamp = max(block_df['Time Found']) - - values_to_drop = ['networkHashrate [Th/s]', 'networkDifficulty [Peta]', - 'poolHashrate [Gh/s]', 'networkType', 'connectedPeers', 'rewardType'] + block_df = reader.block_df # + worker_performace = reader.miner_sample_df + my_worker_performance = worker_performace[worker_performace.miner == wallet] - miner_performance_chart = px.line(miner_performance, + miner_performance_chart = px.line(my_worker_performance, x='created', y='hashrate', color='worker', @@ -235,69 +182,67 @@ def update_charts(n_intervals, table, pathname): xaxis=dict(title='Time', color='#FFFFFF',showgrid=False, showline=False, zeroline=False), yaxis=dict(title='Hashrate', color='#FFFFFF') ) + return [miner_performance_chart] + - my_block_df = block_df[block_df.miner == short_wallet] - try: - latest = max(my_block_df['Time Found']) - except ValueError: - latest = min(block_df['Time Found']) - - if not isinstance(latest, str): - print('triggered') - latest = min(block_df['Time Found']) - print(latest, '1') - - plot = miner_performance_chart - - df = reader.get_all_miner_data(wallet) - # print(wallet) - # print(latest) - latest_data = df[df.created == max(df.created)] - my_data = latest_data[latest_data.my_wallet == True] - my_data = my_data.filter(['worker', 'hashrate', 'sharesPerSecond']) - total_hash = my_data.hashrate.sum() - total_shares = my_data.sharesPerSecond.sum() - ls = ['Totals', total_hash, total_shares] - d = pd.DataFrame([ls], columns=['worker', 'hashrate', 'sharesPerSecond']) - work_data = pd.concat([my_data, d]) - print(latest, 'miningpage latest') - - work_data['ttf'] = [reader.calculate_time_to_find_block(network_difficulty, network_hashrate, hash, latest) for hash in work_data.hashrate] - work_data['effort'] = [reader.calculate_mining_effort(network_difficulty, network_hashrate, hash, latest) for hash in work_data.hashrate] - - work_data['hashrate'] = round(work_data['hashrate'], 3) - work_data['sharesPerSecond'] = round(work_data['sharesPerSecond'], 3) + + @app.callback([Output('table-2', 'data'), + Output('table-title', 'children'),], + [Input('mp-interval-3', 'n_intervals'), + Input('table-dropdown', 'value')], + [State('url', 'pathname')]) + + def update_table(n_intervals, table, pathname): + wallet = unquote(pathname.lstrip('/')) + if wallet != 'Enter Your Address': + short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) + else: + short_wallet = wallet + if table == 'workers': - df = work_data + df = reader.get_latest_worker_samples(False) + df = df[df.miner == wallet] + df = df.filter(['worker', 'hashrate', 'sharesPerSecond', 'Effort', 'TTF']) + df = df.rename(columns={"Effort": "Current Effort [%]", "hashrate": "MH/s", 'TTF': 'TTF [Days]'}) + title_2 = 'WORKER DATA' elif table == 'blocks': + block_df = reader.block_df # + my_block_df = block_df[block_df.miner == wallet] df = my_block_df + print(df.columns) + df = df.filter(['Time Found', 'blockHeight', 'effort [%]', 'reward [erg]', 'Confirmation [%]']) title_2 = 'Your Blocks Found' - else: - df = work_data - title_2 = 'WORKER DATA' columns = [{"name": i, "id": i} for i in df.columns] data = df.to_dict('records') # print(first, second) - return plot, data, title_2 + return data, title_2 def get_layout(reader): - return html.Div([dbc.Container(fluid=True, style={'backgroundColor': background_color, 'padding': '10px', 'justifyContent': 'center', 'fontFamily': 'sans-serif', 'color': '#FFFFFF', 'maxWidth': '960px'}, + md=4 + return html.Div([dbc.Container(fluid=True, style={'backgroundColor': background_color, 'padding': '15px', 'justifyContent': 'center', 'fontFamily': 'sans-serif', 'color': '#FFFFFF', 'maxWidth': '960px'}, children=[ - dcc.Interval(id='mp-interveral-1', interval=60*1000, n_intervals=0), - dcc.Interval(id='mp-interveral-2', interval=60*1000, n_intervals=0), + dcc.Interval(id='mp-interval-1', interval=60*1000, n_intervals=0), + dcc.Interval(id='mp-interval-2', interval=60*1000, n_intervals=0), + dcc.Interval(id='mp-interval-3', interval=60*1000, n_intervals=0), + dcc.Interval(id='mp-interval-4', interval=60*1000, n_intervals=0), html.H1('ERGO Sigmanaut Mining Pool', style={'color': 'white', 'textAlign': 'center',}), - dbc.Row(id='mp-stats', justify='center', style={'padding': '20px'}), - dbc.Row(id='mp-metrics', justify='center', style={'padding': '20px'}), + dbc.Row(id='mp-stats', justify='center',), + # dbc.Row(id='mp-metrics', justify='center', style={'padding': '20px'}), + dbc.Row(justify='center', style={'padding': '20px'}, children=[ + dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s1')],), + dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s2')],), + dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s3')],)]), + html.H2('Worker Hashrate Over Time', style={'color': 'white', 'textAlign': 'center',}), - dcc.Graph(id='chart', style={'backgroundColor': card_color}), + dcc.Graph(id='chart', style={'backgroundColor': card_color, 'padding': '20px'}), html.Div( [ @@ -337,17 +282,11 @@ def get_layout(reader): 'width': '180px', 'maxWidth': '180px', 'whiteSpace': 'normal', 'textAlign': 'left', 'padding': '10px',}, - style_header={'backgroundColor': card_color, 'color': 'white', - 'fontWeight': 'bold', 'textAlign': 'center',}, - style_data={'backgroundColor': card_color, 'color': 'white', - 'border': '1px solid black',}, - style_data_conditional=[{'if': {'column_id': 'status', 'filter_query': '{status} eq confirmed'}, - 'backgroundColor': 'lightgreen', 'color': 'black', 'after': {'content': '" ✔"'}}], - style_as_list_view=True, style_cell_conditional=[{'if': {'column_id': c}, - 'textAlign': 'left'} for c in ['Name', 'status']], - style_header_conditional=[{'if': {'column_id': 'status'}, 'textAlign': 'center'}]) - ]), - ], style={'backgroundColor': card_color}) # This sets the background color for the whole page + style_header=table_style, + style_data=table_style, + + ), + ]),], style={'backgroundColor': card_color}) # This sets the background color for the whole page if __name__ == '__main__': reader = SigmaWalletReader('../conf') diff --git a/layouts/mining_page_1.py b/layouts/mining_page_1.py deleted file mode 100644 index 0fa5e18b..00000000 --- a/layouts/mining_page_1.py +++ /dev/null @@ -1,300 +0,0 @@ -from utils.api_reader import SigmaWalletReader, PriceReader -from utils.dash_utils import image_style, create_pie_chart, create_bar_chart, create_table_component, create_row_card, create_image_text_block, card_style, image_card_style, bottom_row_style, card_color, background_color, large_text_color, small_text_color, bottom_image_style, top_row_style, table_style -from dash import Dash, html, dash_table, dcc, callback_context -from dash.exceptions import PreventUpdate -from urllib.parse import unquote -import dash_bootstrap_components as dbc -import pandas as pd -import plotly.express as px -from dash.dependencies import Input, Output, State -import plotly.graph_objs as go - -from flask_login import LoginManager, UserMixin, login_user -from flask import Flask, request, session, redirect, url_for -from flask_session import Session -debug = False -server = Flask(__name__) -server.config['SECRET_KEY'] = 'your_super_secret_key' # Change this to a random secret key -server.config['SESSION_TYPE'] = 'filesystem' # Example: filesystem-based session storage - -button_color = large_text_color -Session(server) - -price_reader = PriceReader() -# sigma_reader = SigmaWalletReader(config_path="../conf") - -color_discrete_map = { - 'Rolling Effort': 'black', - 'effort': 'white', - 'networkDifficulty': large_text_color -} - -def setup_mining_page_callbacks(app, reader): - @app.callback([Output('mp-stats', 'children'),], - [Input('mp-interval-4', 'n')], - [State('url', 'pathname')]) - - def update_front_row(n, pathname): - - wallet = unquote(pathname.lstrip('/')) - - if wallet != 'Enter Your Address': - short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) - else: - short_wallet = wallet - - worker_df = reader.get_latest_worker_samples(True) - my_worker_df = worker_df[worker_df.Miner == short_wallet] - my_total_hash = round(my_worker_df.Hashrate[0],) - my_effort = my_worker_df.Effort[0] - my_ttf = my_worker_df.TTF[0] - print('ttf', my_ttf, my_effort, my_total_hash) - - block_df = reader.block_df - block_df['miner'] = block_df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - block_df['my_wallet'] = block_df['miner'].apply(lambda address: address == wallet) - my_blocks = block_df[block_df.my_wallet == True] - - - ### GATHERING POOL AND YOUR HASH TTF AND EFFORT ### - pool_effort_text = '{}%'.format(reader.data['poolEffort']) - pool_ttf_text = '{} Days'.format(reader.data['poolTTF']) - pool_hash_text = '{} GH/s'.format(reader.data['poolHashrate']) - - your_effort_text = '{}%'.format(my_effort) - your_ttf_text = '{} Days'.format(my_ttf) - your_hash_text = '{} MH/s'.format(my_total_hash) - - ### CARDS FOR THE ABOVE METRICS - pool_stats = dbc.Col(dbc.Card(style=top_row_style, children=[ - # html.Img(src=image, style=top_image_style), - html.H2('Pool Stats', style={'color': large_text_color, 'textAlign': 'center'}), - dbc.Row([ - dbc.Col([html.H4('Hashrate', style={'color': large_text_color}), html.P(pool_hash_text),]), - dbc.Col([html.H4('TTF', style={'color': large_text_color}), html.P(pool_ttf_text),]), - dbc.Col([html.H4('Effort', style={'color': large_text_color}), html.P(pool_effort_text)])]),]), - style={'marginRight': 'auto', 'marginLeft': 'auto'}) - - your_stats = dbc.Col(dbc.Card(style=top_row_style, children=[ - # html.Img(src=image, style=top_image_style), - html.H2('Miner Stats', style={'color': large_text_color, 'textAlign': 'center'}), - dbc.Row([ - dbc.Col([html.H4('Hashrate', style={'color': large_text_color}), html.P(your_hash_text),]), - dbc.Col([html.H4('TTF', style={'color': large_text_color}), html.P(your_ttf_text),]), - dbc.Col([html.H4('Effort', style={'color': large_text_color}), html.P(your_effort_text)])]),]), - style={'marginRight': 'auto', 'marginLeft': 'auto'}) - - ### GATHER THE NEXT STATS FOR PAYMENT ### - stats = dbc.Row(justify='center', children=[pool_stats, your_stats]) - return [stats] - - @app.callback([ Output('s1', 'children'), Output('s2', 'children'),], - [Input('mp-interval-1', 'n')], - [State('url', 'pathname')]) - - def update_middle(n, pathname): - wallet = unquote(pathname.lstrip('/')) - - ### PAYMENT STATS ### - my_payment = reader.get_miner_payment_stats(wallet) - - payment_images ={ - 'Pending Shares': 'min-payout.png', - 'Pending Balance': 'triangle.png', - 'Total Paid': 'ergo.png', - 'Last Payment': 'coins.png', - 'Price': 'ergo.png', - 'Schema': 'ergo.png', - } - - payment_children = [create_image_text_block(text='{}: {}'.format(key, my_payment[key]), image=payment_images[key]) for key in payment_images.keys() if key != 'lastPaymentLink'] - - - return payment_children[:3], payment_children[3:] - - @app.callback([ - - Output('s3', 'children'),], - [Input('mp-interval-1', 'n')], - [State('url', 'pathname')]) - - def update_outside(n, pathname): - wallet = unquote(pathname.lstrip('/')) - - ### PAYMENT STATS ### - my_payment = reader.get_miner_payment_stats(wallet) - all_payment_stats = [reader.get_miner_payment_stats(wallet) for wallet in reader.get_miner_ls()] - miners = reader.get_miner_ls() - ls = [] - for miner in miners: - d = reader.get_miner_payment_stats(miner) - shares = d['Pending Shares'] - ls.append([miner, shares]) - - df = pd.DataFrame(ls, columns=['Miner', 'Shares']) - total = df.Shares.sum() - df['participation'] = [shares / total for shares in df.Shares] - df['reward'] = df['participation'] * reader.block_reward - my_df = df[df.Miner == wallet] - participation = round(my_df['participation'].values[0] * 100, 3) - - my_payment['Participation [%]']= participation - - payment_images ={'Participation [%]': 'smileys.png', - 'Paid Today': 'ergo.png', - 'lastPaymentLink': 'ergo.png', - } - - payment_children = [create_image_text_block(text='{}: {}'.format(key, my_payment[key]), image=payment_images[key]) for key in payment_images.keys() if key != 'lastPaymentLink'] - link = html.Div(style=bottom_row_style, children=[ - html.Img(src='assets/{}'.format('ergo.png'), style=bottom_image_style), - html.Span(dcc.Link('Last Payment Link', href=my_payment['lastPaymentLink'], target='_blank'), style={'padding': '10px'})]) - - payment_children.append(link) - - md = 4 - - return [payment_children] - - @app.callback([Output('chart', 'figure'),], - [Input('mp-interval-2', 'n_intervals')], - [State('url', 'pathname')]) - - def update_charts(n_intervals, pathname): - wallet = unquote(pathname.lstrip('/')) - - block_df = reader.block_df # - worker_performace = reader.miner_sample_df - print(worker_performace.columns, 'colz') - my_worker_performance = worker_performace[worker_performace.miner == wallet] - print(my_worker_performance) - - - miner_performance_chart = px.line(my_worker_performance, - x='created', - y='hashrate', - color='worker', - labels={'hashrate': 'Hashrate', 'created': 'Time'}, - markers=True) - - miner_performance_chart.update_layout( - paper_bgcolor='rgba(0,0,0,0)', - plot_bgcolor='rgba(0,0,0,0)', - legend_title_text='Miner', - legend=dict(font=dict(color='#FFFFFF')), - titlefont=dict(color='#FFFFFF'), - xaxis=dict(title='Time', color='#FFFFFF',showgrid=False, showline=False, zeroline=False), - yaxis=dict(title='Hashrate', color='#FFFFFF') - ) - return [miner_performance_chart] - - - - @app.callback([Output('table-2', 'data'), - Output('table-title', 'children'),], - [Input('mp-interval-3', 'n_intervals'), - Input('table-dropdown', 'value')], - [State('url', 'pathname')]) - - def update_table(n_intervals, table, pathname): - wallet = unquote(pathname.lstrip('/')) - - if wallet != 'Enter Your Address': - short_wallet = '{}...{}'.format(wallet[:5], wallet[-5:]) - else: - short_wallet = wallet - - if table == 'workers': - df = reader.get_latest_worker_samples(False) - df = df[df.miner == wallet] - df = df.filter(['worker', 'hashrate', 'sharesPerSecond', 'Effort', 'TTF']) - df = df.rename(columns={"Effort": "Current Effort [%]", "hashrate": "MH/s", 'TTF': 'TTF [Days]'}) - - title_2 = 'WORKER DATA' - - elif table == 'blocks': - block_df = reader.block_df # - my_block_df = block_df[block_df.miner == wallet] - df = my_block_df - print(df.columns) - df = df.filter(['Time Found', 'blockHeight', 'effort [%]', 'reward [erg]', 'Confirmation [%]']) - title_2 = 'Your Blocks Found' - - columns = [{"name": i, "id": i} for i in df.columns] - data = df.to_dict('records') - # print(first, second) - return data, title_2 - - -def get_layout(reader): - md=4 - return html.Div([dbc.Container(fluid=True, style={'backgroundColor': background_color, 'padding': '15px', 'justifyContent': 'center', 'fontFamily': 'sans-serif', 'color': '#FFFFFF', 'maxWidth': '960px'}, - children=[ - - dcc.Interval(id='mp-interval-1', interval=60*1000, n_intervals=0), - dcc.Interval(id='mp-interval-2', interval=60*1000, n_intervals=0), - dcc.Interval(id='mp-interval-3', interval=60*1000, n_intervals=0), - dcc.Interval(id='mp-interval-4', interval=60*1000, n_intervals=0), - - html.H1('ERGO Sigmanaut Mining Pool', style={'color': 'white', 'textAlign': 'center',}), - dbc.Row(id='mp-stats', justify='center',), - # dbc.Row(id='mp-metrics', justify='center', style={'padding': '20px'}), - dbc.Row(justify='center', style={'padding': '20px'}, children=[ - dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s1')],), - dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s2')],), - dbc.Col(md=md, style={'padding': '7px'}, children=[dbc.Card(style=bottom_row_style, id='s3')],)]), - - - html.H2('Worker Hashrate Over Time', style={'color': 'white', 'textAlign': 'center',}), - dcc.Graph(id='chart', style={'backgroundColor': card_color, 'padding': '20px'}), - - html.Div( - [ - html.Div( - html.H1( - id='table-title', - children='Please select an option', - style={'fontSize': '24px'} - ), - style={'flex': '1'} - ), - html.Div( - dcc.Dropdown( - id='table-dropdown', - options=[ - {'label': 'Your Worker Data', 'value': 'workers'}, - {'label': 'Your Block Data', 'value': 'blocks'} - ], - value='workers', # Default value - style={'width': '300px', 'color': 'black'} - ), - style={'flex': '1'} - ) - ], - style={ - 'display': 'flex', - 'justifyContent': 'space-between', - 'alignItems': 'center', - 'padding': '10px' - } - ), - - # html.Div(children=[html.H2('Block Statistics'), - dash_table.DataTable(id='table-2', - style_table={'overflowX': 'auto'}, - style_cell={'height': 'auto', 'minWidth': '180px', - 'width': '180px', 'maxWidth': '180px', - 'whiteSpace': 'normal', 'textAlign': 'left', - 'padding': '10px',}, - style_header=table_style, - style_data=table_style, - - ), - ]),], style={'backgroundColor': card_color}) # This sets the background color for the whole page - -if __name__ == '__main__': - reader = SigmaWalletReader('../conf') - app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) - app.layout = get_layout(reader) - setup_front_page_callbacks(app, reader) - app.run_server(debug=True) \ No newline at end of file diff --git a/prototype-Copy1.ipynb b/prototype-Copy1.ipynb deleted file mode 100644 index eb909b34..00000000 --- a/prototype-Copy1.ipynb +++ /dev/null @@ -1,1215 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 11, - "id": "9e4f1413-71a8-4b4c-8ca7-ed6d5cd46f9e", - "metadata": {}, - "outputs": [], - "source": [ - "from utils.api_reader import SigmaWalletReader" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "c71066a8-7611-4430-aa3a-0c306eca473c", - "metadata": {}, - "outputs": [], - "source": [ - "reader = SigmaWalletReader(config_path=\"../conf\")\n", - "wallet = '9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPVApYkk'" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "5bb15058-adf9-4463-bb36-012595c771a1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "16825133055.999998 hashhh 1655452194570240.0\n" - ] - } - ], - "source": [ - "reader.update_data()" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "6987e3f5-11cc-4844-bc08-ba42afefc376", - "metadata": { - "scrolled": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "210887572100000.0 hashhh 1655452194570240.0\n", - "2357468882733333.0 hashhh 1655452194570240.0\n", - "363915129166666.7 hashhh 1655452194570240.0\n", - "1227725760300000.0 hashhh 1655452194570240.0\n", - "1079156732599999.9 hashhh 1655452194570240.0\n", - "2290568409166666.5 hashhh 1655452194570240.0\n", - "312995546633333.3 hashhh 1655452194570240.0\n", - "829340518766666.6 hashhh 1655452194570240.0\n", - "711026902633333.4 hashhh 1655452194570240.0\n", - "805956842166666.6 hashhh 1655452194570240.0\n", - "881910092300000.0 hashhh 1655452194570240.0\n", - "1010405895033333.2 hashhh 1655452194570240.0\n", - "272296153266666.66 hashhh 1655452194570240.0\n", - "1298077455300000.0 hashhh 1655452194570240.0\n", - "697875148233333.4 hashhh 1655452194570240.0\n", - "702789966400000.0 hashhh 1655452194570240.0\n", - "594218703500000.0 hashhh 1655452194570240.0\n", - "221129362200000.0 hashhh 1655452194570240.0\n", - "156620578633333.3 hashhh 1655452194570240.0\n", - "460263743033333.4 hashhh 1655452194570240.0\n", - "335540494166666.7 hashhh 1655452194570240.0\n", - "116683502633333.34 hashhh 1655452194570240.0\n", - "267024495200000.0 hashhh 1655452194570240.0\n", - "latest\n", - "5239155000.0 hashhh 1655452194570240.0\n", - "latest\n", - "3432905000.0 hashhh 1655452194570240.0\n", - "latest\n", - "3409300000.0 hashhh 1655452194570240.0\n", - "latest\n", - "272296000.0 hashhh 1655452194570240.0\n", - "latest\n", - "1298077000.0 hashhh 1655452194570240.0\n", - "1400665000.0 hashhh 1655452194570240.0\n", - "latest\n", - "971969000.0 hashhh 1655452194570240.0\n", - "latest\n", - "460264000.0 hashhh 1655452194570240.0\n", - "335540000.0 hashhh 1655452194570240.0\n", - "latest\n", - "116684000.0 hashhh 1655452194570240.0\n", - "267024000.0 hashhh 1655452194570240.0\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:188: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " # df['ttf'] = [self.calculate_time_to_find_block(self.data['networkDifficulty'], self.data['networkHashrate'], hashrate, self.latest_block) for hashrate in df.hashrate]\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:189: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " # df['effort'] = [self.calculate_mining_effort(self.data['networkDifficulty'], self.data['networkHashrate'], hashrate, self.latest_block) for hashrate in df.hashrate]\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:191: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['hashrate'] = round(df['hashrate'] / 1e6, 3)\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:192: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['sharesPerSecond'] = round(df['sharesPerSecond'], 3)\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
MinerHashrateSharesPerSecondEffortTTF
09ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...5239.1550.32153.1413.657
19i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ...3432.9050.2033.1585.581
29gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...3409.3000.2948.2885.620
39hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq...272.2960.061.32170.366
49gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4...1298.0770.0756.00814.761
59exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ...1400.6650.14150.87413.679
69i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ...971.9690.1489.99319.713
79g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K...460.2640.075.17641.629
89hYeUWUG2dAM6sZb9vr5qgF1gACEGQPLN9cbXjxERmJS89...335.5400.0636.14357.103
99iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z...116.6840.0212.569164.207
109eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZed...267.0240.0628.76371.755
\n", - "
" - ], - "text/plain": [ - " Miner Hashrate \\\n", - "0 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 5239.155 \n", - "1 9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ... 3432.905 \n", - "2 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... 3409.300 \n", - "3 9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq... 272.296 \n", - "4 9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4... 1298.077 \n", - "5 9exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ... 1400.665 \n", - "6 9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ... 971.969 \n", - "7 9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K... 460.264 \n", - "8 9hYeUWUG2dAM6sZb9vr5qgF1gACEGQPLN9cbXjxERmJS89... 335.540 \n", - "9 9iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z... 116.684 \n", - "10 9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZed... 267.024 \n", - "\n", - " SharesPerSecond Effort TTF \n", - "0 0.32 153.141 3.657 \n", - "1 0.20 33.158 5.581 \n", - "2 0.29 48.288 5.620 \n", - "3 0.06 1.321 70.366 \n", - "4 0.07 56.008 14.761 \n", - "5 0.14 150.874 13.679 \n", - "6 0.14 89.993 19.713 \n", - "7 0.07 5.176 41.629 \n", - "8 0.06 36.143 57.103 \n", - "9 0.02 12.569 164.207 \n", - "10 0.06 28.763 71.755 " - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "df = reader.get_latest_worker_samples(True)\n", - "df" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "92b3ad52-a01b-4e67-9cc2-286358b7f659", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "210887572100000.0 hashhh 1655452194570240.0\n", - "2357468882733333.0 hashhh 1655452194570240.0\n", - "363915129166666.7 hashhh 1655452194570240.0\n", - "1227725760300000.0 hashhh 1655452194570240.0\n", - "1079156732599999.9 hashhh 1655452194570240.0\n", - "2290568409166666.5 hashhh 1655452194570240.0\n", - "312995546633333.3 hashhh 1655452194570240.0\n", - "829340518766666.6 hashhh 1655452194570240.0\n", - "711026902633333.4 hashhh 1655452194570240.0\n", - "805956842166666.6 hashhh 1655452194570240.0\n", - "881910092300000.0 hashhh 1655452194570240.0\n", - "1010405895033333.2 hashhh 1655452194570240.0\n", - "272296153266666.66 hashhh 1655452194570240.0\n", - "1298077455300000.0 hashhh 1655452194570240.0\n", - "697875148233333.4 hashhh 1655452194570240.0\n", - "702789966400000.0 hashhh 1655452194570240.0\n", - "594218703500000.0 hashhh 1655452194570240.0\n", - "221129362200000.0 hashhh 1655452194570240.0\n", - "156620578633333.3 hashhh 1655452194570240.0\n", - "460263743033333.4 hashhh 1655452194570240.0\n", - "335540494166666.7 hashhh 1655452194570240.0\n", - "116683502633333.34 hashhh 1655452194570240.0\n", - "267024495200000.0 hashhh 1655452194570240.0\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:188: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['ttf'] = [self.calculate_time_to_find_block(self.data['networkDifficulty'], self.data['networkHashrate'], hashrate, self.latest_block) for hashrate in df.hashrate]\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:189: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['effort'] = [self.calculate_mining_effort(self.data['networkDifficulty'], self.data['networkHashrate'], hashrate, self.latest_block) for hashrate in df.hashrate]\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:191: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['hashrate'] = round(df['hashrate'] / 1e6, 3)\n", - "/Users/marctheshark/Documents/ergo/sigmanaut-mining-pool-ui/utils/api_reader.py:192: SettingWithCopyWarning: \n", - "A value is trying to be set on a copy of a slice from a DataFrame.\n", - "Try using .loc[row_indexer,col_indexer] = value instead\n", - "\n", - "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", - " df['sharesPerSecond'] = round(df['sharesPerSecond'], 3)\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
createdworkerhashratesharesPerSecondminerttfeffort
1022024-04-05T20:00:00ZBlueSky210.8880.0449ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...0.01.014353e+06
1032024-04-05T20:00:00ZGRAYSPEAK2357.4690.0759ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...0.01.133925e+07
1042024-04-05T20:00:00ZLAPLATAPEAK363.9150.0639ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...0.01.750405e+06
1052024-04-05T20:00:00ZMT-MASSIVE1227.7260.0709ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...0.05.905269e+06
1062024-04-05T20:00:00ZPIKESPEAK1079.1570.0739ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...0.05.190663e+06
662024-04-05T20:00:00ZFastMiner2290.5680.0709i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ...0.01.101746e+07
672024-04-05T20:00:00Zqxfanclub312.9960.0629i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ...0.01.505485e+06
682024-04-05T20:00:00Zrig4116EB829.3410.0699i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ...0.03.989066e+06
882024-04-05T20:00:00Z3x_3060_3x_3060ti711.0270.0709gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...0.03.419986e+06
892024-04-05T20:00:00Z6x_ASUS805.9570.0739gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...0.03.876592e+06
902024-04-05T20:00:00Z6x_GIGABYTE881.9100.0779gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...0.04.241922e+06
912024-04-05T20:00:00Z6x_MIXED1010.4060.0729gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...0.04.859977e+06
252024-04-05T20:00:00ZKraken272.2960.0559hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq...0.01.309724e+06
222024-04-05T20:00:00Zrig0874391298.0770.0749gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4...0.06.243656e+06
502024-04-05T20:00:00ZBig6697.8750.0749exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ...0.03.356727e+06
512024-04-05T20:00:00ZSmall5702.7900.0669exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ...0.03.380367e+06
612024-04-05T20:00:00ZGimli594.2190.0649i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ...0.02.858148e+06
622024-04-05T20:00:00ZHeartofGold221.1290.0469i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ...0.01.063616e+06
632024-04-05T20:00:00ZOldMan156.6210.0349i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ...0.07.533333e+05
222024-04-05T20:00:00ZEpycDownstairs460.2640.0689g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K...0.02.213834e+06
152024-04-05T20:00:00ZAffable335.5400.0629hYeUWUG2dAM6sZb9vr5qgF1gACEGQPLN9cbXjxERmJS89...0.01.613925e+06
222024-04-05T20:00:00Zrustinmyeye116.6840.0259iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z...0.05.612389e+05
222024-04-05T20:00:00Zqx3090267.0240.0579eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZed...0.01.284368e+06
\n", - "
" - ], - "text/plain": [ - " created worker hashrate sharesPerSecond \\\n", - "102 2024-04-05T20:00:00Z BlueSky 210.888 0.044 \n", - "103 2024-04-05T20:00:00Z GRAYSPEAK 2357.469 0.075 \n", - "104 2024-04-05T20:00:00Z LAPLATAPEAK 363.915 0.063 \n", - "105 2024-04-05T20:00:00Z MT-MASSIVE 1227.726 0.070 \n", - "106 2024-04-05T20:00:00Z PIKESPEAK 1079.157 0.073 \n", - "66 2024-04-05T20:00:00Z FastMiner 2290.568 0.070 \n", - "67 2024-04-05T20:00:00Z qxfanclub 312.996 0.062 \n", - "68 2024-04-05T20:00:00Z rig4116EB 829.341 0.069 \n", - "88 2024-04-05T20:00:00Z 3x_3060_3x_3060ti 711.027 0.070 \n", - "89 2024-04-05T20:00:00Z 6x_ASUS 805.957 0.073 \n", - "90 2024-04-05T20:00:00Z 6x_GIGABYTE 881.910 0.077 \n", - "91 2024-04-05T20:00:00Z 6x_MIXED 1010.406 0.072 \n", - "25 2024-04-05T20:00:00Z Kraken 272.296 0.055 \n", - "22 2024-04-05T20:00:00Z rig087439 1298.077 0.074 \n", - "50 2024-04-05T20:00:00Z Big6 697.875 0.074 \n", - "51 2024-04-05T20:00:00Z Small5 702.790 0.066 \n", - "61 2024-04-05T20:00:00Z Gimli 594.219 0.064 \n", - "62 2024-04-05T20:00:00Z HeartofGold 221.129 0.046 \n", - "63 2024-04-05T20:00:00Z OldMan 156.621 0.034 \n", - "22 2024-04-05T20:00:00Z EpycDownstairs 460.264 0.068 \n", - "15 2024-04-05T20:00:00Z Affable 335.540 0.062 \n", - "22 2024-04-05T20:00:00Z rustinmyeye 116.684 0.025 \n", - "22 2024-04-05T20:00:00Z qx3090 267.024 0.057 \n", - "\n", - " miner ttf effort \n", - "102 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 0.0 1.014353e+06 \n", - "103 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 0.0 1.133925e+07 \n", - "104 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 0.0 1.750405e+06 \n", - "105 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 0.0 5.905269e+06 \n", - "106 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... 0.0 5.190663e+06 \n", - "66 9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ... 0.0 1.101746e+07 \n", - "67 9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ... 0.0 1.505485e+06 \n", - "68 9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ... 0.0 3.989066e+06 \n", - "88 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... 0.0 3.419986e+06 \n", - "89 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... 0.0 3.876592e+06 \n", - "90 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... 0.0 4.241922e+06 \n", - "91 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... 0.0 4.859977e+06 \n", - "25 9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq... 0.0 1.309724e+06 \n", - "22 9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4... 0.0 6.243656e+06 \n", - "50 9exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ... 0.0 3.356727e+06 \n", - "51 9exkqG2KBpdeHKby84pSehSZt9sKQitAqjuguHXdd25eEJ... 0.0 3.380367e+06 \n", - "61 9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ... 0.0 2.858148e+06 \n", - "62 9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ... 0.0 1.063616e+06 \n", - "63 9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ... 0.0 7.533333e+05 \n", - "22 9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K... 0.0 2.213834e+06 \n", - "15 9hYeUWUG2dAM6sZb9vr5qgF1gACEGQPLN9cbXjxERmJS89... 0.0 1.613925e+06 \n", - "22 9iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z... 0.0 5.612389e+05 \n", - "22 9eZPTmn8zp5GJ7KZwTo8cEuxNdezWaY3hBbLeWid7EAZed... 0.0 1.284368e+06 " - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "reader.get_latest_worker_samples(False)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "9ef87162-3fd1-49c4-a1cb-373a2584b6ca", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "224.2866" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "2.242866e+08 / 1e6" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "50762a91-54c0-468c-9c0b-ac16af7008a9", - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
createdworkerhashratesharesPerSecondminer
\n", - "
" - ], - "text/plain": [ - "Empty DataFrame\n", - "Columns: [created, worker, hashrate, sharesPerSecond, miner]\n", - "Index: []" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "reader.miner_latest_samples" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "cc7f2906-58a8-4703-b5de-7c42074cde9f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
poolIdblockHeightnetworkDifficultystatusconfirmationProgressefforttransactionConfirmationDatarewardinfoLinkhashminersourcecreatedTime FoundRolling Effort
0ErgoSigmanauts1235990387916.169692confirmed10.52520058216259db39230.010000https://explorer.ergoplatform.com/en/blocks/bd...bd3099462e5eba95a4e8e809232f6788f2664e4a344eae...9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq...ErgoSigmanauts2024-04-04T23:46:44.506203Z2024-04-04 23:46:440.525000
1ErgoSigmanauts1235365466883.931372confirmed10.169d0db3663848642f530.068900https://explorer.ergoplatform.com/en/blocks/00...000eacceb597c08feeb2a67ea6f0b804d9dc185c0e0630...9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ...ErgoSigmanauts2024-04-04T01:40:19.004614Z2024-04-04 01:40:190.347000
2ErgoSigmanauts1235136433886.497034confirmed10.349d4481db8a168230330.007660https://explorer.ergoplatform.com/en/blocks/ba...babafdf183a977d3ef1cf8823f241e3393ac0472f9a00e...9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K...ErgoSigmanauts2024-04-03T18:22:18.298737Z2024-04-03 18:22:180.347667
3ErgoSigmanauts1234733425282.536901confirmed11.927d43cfb8db6bde05730.008316https://explorer.ergoplatform.com/en/blocks/85...85775b03bae1f4c46c3b444bd511838d5fb9cd326c8462...9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...ErgoSigmanauts2024-04-03T04:57:28.98427Z2024-04-03 04:57:280.742500
4ErgoSigmanauts1232662385380.245572confirmed10.026d88e000ab46f7e8a30.000000https://explorer.ergoplatform.com/en/blocks/bf...bfce9fe97cbc219e80858ee257f664fd3ad9ff713ed12c...9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...ErgoSigmanauts2024-03-31T07:40:29.504233Z2024-03-31 07:40:290.599200
5ErgoSigmanauts1232628363957.496239confirmed10.237d10ffd6af9eca40630.000000https://explorer.ergoplatform.com/en/blocks/48...48044bb6835294495eb17744326b63f3183a629ab44767...9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K...ErgoSigmanauts2024-03-31T06:53:18.263557Z2024-03-31 06:53:180.538833
6ErgoSigmanauts1232487360630.583506confirmed11.013dee5be1bf40de25e30.013800https://explorer.ergoplatform.com/en/blocks/0f...0f56bc5a2f2b9f179c81feeab3022723bc60df72ad4121...9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq...ErgoSigmanauts2024-03-31T02:11:27.849648Z2024-03-31 02:11:270.606571
7ErgoSigmanauts1231651367785.409859confirmed10.467daa5cc820eedd3d930.001500https://explorer.ergoplatform.com/en/blocks/20...20b806d4bd9cc58f6cc04ffdeaffd6e68c07f66e422e78...9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...ErgoSigmanauts2024-03-29T22:22:38.975286Z2024-03-29 22:22:380.589125
8ErgoSigmanauts1231144405099.842403confirmed10.329d88f00142c1483c130.002000https://explorer.ergoplatform.com/en/blocks/27...278a4a533165aa5c63f8f79bb8a1ab9d29e1a62d254139...9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV...ErgoSigmanauts2024-03-29T04:26:22.21146Z2024-03-29 04:26:220.560222
9ErgoSigmanauts1230782360986.500966confirmed10.031d00cd5ba5f2b167c30.088260https://explorer.ergoplatform.com/en/blocks/33...3360f32693fd991c229e6a3b095eb2ff6e0367dcbac370...9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ...ErgoSigmanauts2024-03-28T16:41:02.906182Z2024-03-28 16:41:020.507300
10ErgoSigmanauts1230749360986.500966confirmed10.287d8a48cee009b608c30.006550https://explorer.ergoplatform.com/en/blocks/2e...2e2b04e088834393eafa5aac17d0fc641f4a188d6dc873...9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4...ErgoSigmanauts2024-03-28T15:40:37.400137Z2024-03-28 15:40:370.487273
11ErgoSigmanauts1230547434381.378191confirmed10.797d6c1191549ab2f0730.027600https://explorer.ergoplatform.com/en/blocks/c5...c5886b3606b842b4a0ecaeda2d6270ac3238e7e0da37d2...9fYvQMsMN3NNaw33cAFnRdyHy1DpxtxfADvGqUV3ocLptw...ErgoSigmanauts2024-03-28T08:26:49.370775Z2024-03-28 08:26:490.513083
12ErgoSigmanauts1230104347635.796935confirmed14.753d153e8105c7c0b5730.001000https://explorer.ergoplatform.com/en/blocks/b0...b03937a8404d47fed3d7050a93a6e6b940100e4c008a66...9fYvQMsMN3NNaw33cAFnRdyHy1DpxtxfADvGqUV3ocLptw...ErgoSigmanauts2024-03-27T18:07:25.358611Z2024-03-27 18:07:250.839231
13ErgoSigmanauts1223980416310.690227confirmed10.896300b000932aead3a30.007862https://explorer.ergoplatform.com/en/blocks/83...83c740633d4aa9e61775dcab0d2ef20dd4d11c275424fa...9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ...ErgoSigmanauts2024-03-19T04:19:20.685251Z2024-03-19 04:19:200.843286
14ErgoSigmanauts1221911421209.622611confirmed12.867705c89a6a4e552cf30.007100https://explorer.ergoplatform.com/en/blocks/47...47dd2792f0fd255fc8fc4b0a12903b351245fb7083ea5e...9iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z...ErgoSigmanauts2024-03-16T06:45:27.859919Z2024-03-16 06:45:270.978200
\n", - "
" - ], - "text/plain": [ - " poolId blockHeight networkDifficulty status \\\n", - "0 ErgoSigmanauts 1235990 387916.169692 confirmed \n", - "1 ErgoSigmanauts 1235365 466883.931372 confirmed \n", - "2 ErgoSigmanauts 1235136 433886.497034 confirmed \n", - "3 ErgoSigmanauts 1234733 425282.536901 confirmed \n", - "4 ErgoSigmanauts 1232662 385380.245572 confirmed \n", - "5 ErgoSigmanauts 1232628 363957.496239 confirmed \n", - "6 ErgoSigmanauts 1232487 360630.583506 confirmed \n", - "7 ErgoSigmanauts 1231651 367785.409859 confirmed \n", - "8 ErgoSigmanauts 1231144 405099.842403 confirmed \n", - "9 ErgoSigmanauts 1230782 360986.500966 confirmed \n", - "10 ErgoSigmanauts 1230749 360986.500966 confirmed \n", - "11 ErgoSigmanauts 1230547 434381.378191 confirmed \n", - "12 ErgoSigmanauts 1230104 347635.796935 confirmed \n", - "13 ErgoSigmanauts 1223980 416310.690227 confirmed \n", - "14 ErgoSigmanauts 1221911 421209.622611 confirmed \n", - "\n", - " confirmationProgress effort transactionConfirmationData reward \\\n", - "0 1 0.525 20058216259db392 30.010000 \n", - "1 1 0.169 d0db3663848642f5 30.068900 \n", - "2 1 0.349 d4481db8a1682303 30.007660 \n", - "3 1 1.927 d43cfb8db6bde057 30.008316 \n", - "4 1 0.026 d88e000ab46f7e8a 30.000000 \n", - "5 1 0.237 d10ffd6af9eca406 30.000000 \n", - "6 1 1.013 dee5be1bf40de25e 30.013800 \n", - "7 1 0.467 daa5cc820eedd3d9 30.001500 \n", - "8 1 0.329 d88f00142c1483c1 30.002000 \n", - "9 1 0.031 d00cd5ba5f2b167c 30.088260 \n", - "10 1 0.287 d8a48cee009b608c 30.006550 \n", - "11 1 0.797 d6c1191549ab2f07 30.027600 \n", - "12 1 4.753 d153e8105c7c0b57 30.001000 \n", - "13 1 0.896 300b000932aead3a 30.007862 \n", - "14 1 2.867 705c89a6a4e552cf 30.007100 \n", - "\n", - " infoLink \\\n", - "0 https://explorer.ergoplatform.com/en/blocks/bd... \n", - "1 https://explorer.ergoplatform.com/en/blocks/00... \n", - "2 https://explorer.ergoplatform.com/en/blocks/ba... \n", - "3 https://explorer.ergoplatform.com/en/blocks/85... \n", - "4 https://explorer.ergoplatform.com/en/blocks/bf... \n", - "5 https://explorer.ergoplatform.com/en/blocks/48... \n", - "6 https://explorer.ergoplatform.com/en/blocks/0f... \n", - "7 https://explorer.ergoplatform.com/en/blocks/20... \n", - "8 https://explorer.ergoplatform.com/en/blocks/27... \n", - "9 https://explorer.ergoplatform.com/en/blocks/33... \n", - "10 https://explorer.ergoplatform.com/en/blocks/2e... \n", - "11 https://explorer.ergoplatform.com/en/blocks/c5... \n", - "12 https://explorer.ergoplatform.com/en/blocks/b0... \n", - "13 https://explorer.ergoplatform.com/en/blocks/83... \n", - "14 https://explorer.ergoplatform.com/en/blocks/47... \n", - "\n", - " hash \\\n", - "0 bd3099462e5eba95a4e8e809232f6788f2664e4a344eae... \n", - "1 000eacceb597c08feeb2a67ea6f0b804d9dc185c0e0630... \n", - "2 babafdf183a977d3ef1cf8823f241e3393ac0472f9a00e... \n", - "3 85775b03bae1f4c46c3b444bd511838d5fb9cd326c8462... \n", - "4 bfce9fe97cbc219e80858ee257f664fd3ad9ff713ed12c... \n", - "5 48044bb6835294495eb17744326b63f3183a629ab44767... \n", - "6 0f56bc5a2f2b9f179c81feeab3022723bc60df72ad4121... \n", - "7 20b806d4bd9cc58f6cc04ffdeaffd6e68c07f66e422e78... \n", - "8 278a4a533165aa5c63f8f79bb8a1ab9d29e1a62d254139... \n", - "9 3360f32693fd991c229e6a3b095eb2ff6e0367dcbac370... \n", - "10 2e2b04e088834393eafa5aac17d0fc641f4a188d6dc873... \n", - "11 c5886b3606b842b4a0ecaeda2d6270ac3238e7e0da37d2... \n", - "12 b03937a8404d47fed3d7050a93a6e6b940100e4c008a66... \n", - "13 83c740633d4aa9e61775dcab0d2ef20dd4d11c275424fa... \n", - "14 47dd2792f0fd255fc8fc4b0a12903b351245fb7083ea5e... \n", - "\n", - " miner source \\\n", - "0 9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq... ErgoSigmanauts \n", - "1 9i3P4Ah9jp7nnSNMg6gxjXXHEWjkkBbPJR5RLRkMwEt3DZ... ErgoSigmanauts \n", - "2 9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K... ErgoSigmanauts \n", - "3 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... ErgoSigmanauts \n", - "4 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... ErgoSigmanauts \n", - "5 9g4f585vPtgA5PKhSRcaPBhtfW3HYRw2qe3aemxxnD5Y1K... ErgoSigmanauts \n", - "6 9hT1c9NNUeNF8nxcE4zyzb6Ui2ypFcSjNKxrSj3hJkQKvq... ErgoSigmanauts \n", - "7 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... ErgoSigmanauts \n", - "8 9ehJZvPDgvCNNd2zTQHxnSpcCAtb1kHbEN1VAgeoRD5DPV... ErgoSigmanauts \n", - "9 9gXo8m2VyHvQ3FGvCg1GNWfyM5uX27BEKNCXDjQ6GiFsMJ... ErgoSigmanauts \n", - "10 9gwk97nY8Uc6kLcSYs4ueWttY5EKyfsrbiyVQWFdUaWvd4... ErgoSigmanauts \n", - "11 9fYvQMsMN3NNaw33cAFnRdyHy1DpxtxfADvGqUV3ocLptw... ErgoSigmanauts \n", - "12 9fYvQMsMN3NNaw33cAFnRdyHy1DpxtxfADvGqUV3ocLptw... ErgoSigmanauts \n", - "13 9i8wsL9HYe4wRtuxXtnvki31uGJd6avKoQ79BXbz2sHWNZ... ErgoSigmanauts \n", - "14 9iQS22vfWdF2N84Lvv9jgAMFGLyL7t17SWbHGEfaddaG7Z... ErgoSigmanauts \n", - "\n", - " created Time Found Rolling Effort \n", - "0 2024-04-04T23:46:44.506203Z 2024-04-04 23:46:44 0.525000 \n", - "1 2024-04-04T01:40:19.004614Z 2024-04-04 01:40:19 0.347000 \n", - "2 2024-04-03T18:22:18.298737Z 2024-04-03 18:22:18 0.347667 \n", - "3 2024-04-03T04:57:28.98427Z 2024-04-03 04:57:28 0.742500 \n", - "4 2024-03-31T07:40:29.504233Z 2024-03-31 07:40:29 0.599200 \n", - "5 2024-03-31T06:53:18.263557Z 2024-03-31 06:53:18 0.538833 \n", - "6 2024-03-31T02:11:27.849648Z 2024-03-31 02:11:27 0.606571 \n", - "7 2024-03-29T22:22:38.975286Z 2024-03-29 22:22:38 0.589125 \n", - "8 2024-03-29T04:26:22.21146Z 2024-03-29 04:26:22 0.560222 \n", - "9 2024-03-28T16:41:02.906182Z 2024-03-28 16:41:02 0.507300 \n", - "10 2024-03-28T15:40:37.400137Z 2024-03-28 15:40:37 0.487273 \n", - "11 2024-03-28T08:26:49.370775Z 2024-03-28 08:26:49 0.513083 \n", - "12 2024-03-27T18:07:25.358611Z 2024-03-27 18:07:25 0.839231 \n", - "13 2024-03-19T04:19:20.685251Z 2024-03-19 04:19:20 0.843286 \n", - "14 2024-03-16T06:45:27.859919Z 2024-03-16 06:45:27 0.978200 " - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "reader.block_df" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a347b092-cf47-472c-86b3-9cc76d6b42de", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.19" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/prototype.ipynb b/prototype.ipynb index bf24823c..190d7dd7 100644 --- a/prototype.ipynb +++ b/prototype.ipynb @@ -4,24 +4,40 @@ "cell_type": "code", "execution_count": 1, "id": "9e4f1413-71a8-4b4c-8ca7-ed6d5cd46f9e", - "metadata": {}, + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "from utils.api_reader import SigmaWalletReader" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "df7966d0-470e-40e6-9a89-a04f48d4233a", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, "outputs": [ { - "ename": "ImportError", - "evalue": "Unable to import required dependencies:\nnumpy: No module named 'numpy'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[1], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mutils\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mapi_reader\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m SigmaWalletReader\n", - "File \u001b[0;32m~/Documents/ergo/sigma-dashboard/utils/api_reader.py:4\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mhydra\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m compose, initialize\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01momegaconf\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m DictConfig, OmegaConf\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mpandas\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m DataFrame, concat, to_datetime\n\u001b[1;32m 5\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mpycoingecko\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m CoinGeckoAPI\n\u001b[1;32m 6\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdatetime\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m datetime\n", - "File \u001b[0;32m~/.local/lib/python3.10/site-packages/pandas/__init__.py:19\u001b[0m\n\u001b[1;32m 16\u001b[0m _missing_dependencies\u001b[38;5;241m.\u001b[39mappend(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m_dependency\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m_e\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 18\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m _missing_dependencies: \u001b[38;5;66;03m# pragma: no cover\u001b[39;00m\n\u001b[0;32m---> 19\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m(\n\u001b[1;32m 20\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUnable to import required dependencies:\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m+\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;241m.\u001b[39mjoin(_missing_dependencies)\n\u001b[1;32m 21\u001b[0m )\n\u001b[1;32m 22\u001b[0m \u001b[38;5;28;01mdel\u001b[39;00m _hard_dependencies, _dependency, _missing_dependencies\n\u001b[1;32m 24\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 25\u001b[0m \u001b[38;5;66;03m# numpy compat\u001b[39;00m\n", - "\u001b[0;31mImportError\u001b[0m: Unable to import required dependencies:\nnumpy: No module named 'numpy'" + "name": "stdout", + "output_type": "stream", + "text": [ + "Requirement already satisfied: numpy in /home/whaleshark/miniconda3/lib/python3.12/site-packages (1.26.4)\n" ] } ], "source": [ - "from utils.api_reader import SigmaWalletReader" + "!pip install numpy" ] }, { @@ -40,7 +56,9 @@ "id": "29e42d9b-3327-46e2-b91e-7d10043950f6", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "import numpy" + ] }, { "cell_type": "code", diff --git a/prototype2.ipynb b/prototype2.ipynb deleted file mode 100644 index a58dd35d..00000000 --- a/prototype2.ipynb +++ /dev/null @@ -1,77 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 3, - "id": "04133c5d-935a-41f2-be1e-59be26e1ac57", - "metadata": {}, - "outputs": [ - { - "ename": "ModuleNotFoundError", - "evalue": "No module named 'utils'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[3], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mutils\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mapi_reader\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m SigmaWalletReader\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'utils'" - ] - } - ], - "source": [ - "from utils.api_reader import SigmaWalletReader" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "f817add3-92e9-4f1d-99e5-717fdad0776b", - "metadata": {}, - "outputs": [ - { - "ename": "ModuleNotFoundError", - "evalue": "No module named 'utils'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[4], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mutils\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mapi_reader\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m SigmaWalletReader\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'utils'" - ] - } - ], - "source": [ - "from utils.api_reader import SigmaWalletReader" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6f24caa8-dbfa-4d25-9be4-e62adda30c42", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.19" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/response_df.csv b/response_df.csv deleted file mode 100644 index a28a3e4c..00000000 --- a/response_df.csv +++ /dev/null @@ -1,5 +0,0 @@ -,Time Found,networkDifficulty,variable,value -0,2024-03-16 06:45:27,421209.62261050055,Response,2.86749 -1,2024-03-19 04:19:20,416310.69022704655,Response,1.8815 -2,2024-03-16 06:45:27,421209.62261050055,effort,2.86749 -3,2024-03-19 04:19:20,416310.69022704655,effort,0.89551 diff --git a/utils/__pycache__/api_reader.cpython-310.pyc b/utils/__pycache__/api_reader.cpython-310.pyc index 013f004b57607805c4d56b47056a4b38c26ca3a6..72db171b6329a829dc76d0451d7fe095ce036e56 100644 GIT binary patch delta 5223 zcmZ`-X>c6H6`t;$9nH?(((0CF$ynIqLpV6TgnVKf5{wa%4A{nO2K7i@d9}Ol8QIn{ z%TgtSl`<|cT`6+#L!v?ws7h4`Rpj_Z4*sM<5fXCLkPt#rp;VQF6sZCX#Cfl0by!8b zo^QI}d;Plm_3QWE=(TC`;ZUL&j~fd7JM-t2Bj&Eli4OAU<@KkoXZo@9EeeY;7KZ zH;(5Dxx(niQn8rdIFS?oC7mQLR?tUCgZKvB)DVX;eq_{kv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`4-c= z?a?raco;Ey16j}5wwl=ulSYdc|20!gcom95Z}TMeFRh&9Ynz|k|DXss(`D-DLJsx0898@W4Fw$QJ$#5 zsWgFf3xnBWl~I@9#$cFoIAAc@l);(jpYiZC{y&QeQXcmIK8xA) zJVB7czxjIKpVR1lq*0H=c;$+&;-*=J7`?NftVY;QVZ?Uy0krFb1cwMn-}(r_SJ6G0 zTnu&h407lAeVF;6iweoW419ncA0(jPNCzxEMDQ?y%=HLMvjEAIaE&d=+S`pm3iu18 z^#FyPv|fTQ#(dXk-3A;lZf)X!-4@~N`&yk+HIf10Asg3wG&h6)fQGIi4PyvZ2Mu2sLyi= zVnhjniZ&wZ$N$2+=(_+QIchxv+{~PQ6oIrd(;tvu-FMA7%0`zrgu042|HUZ;@T4-h^xpcJjH><)Hs*juB10GTj4>+bpD`Z z4wqAGW5UU_d`y#mbK6N{(SL{gO$ov%u1VTrsEc7Qd_MBF`<>pSJ8^usiMCJ`cXznM zkK$&y!~7~1Nd<7UNhX%?WbQFiTVRJdW~Y*(3ZsT@N}kAIe?HDvlJ_EB5Aq_pH3my3 z&6|yl+`a*l*R!M7SGWU234UF`kkkD#d3KDP*8x|uUmxWn9wK;{;5P~O5c~~-%LMAA5&Q(fNTZh06uUeEZ~(uE z-W5Mn_WY{fC_LnU%s=A$g(v;8zsH~UXZ(tP)c?!=DgSZ*Q9me^WZc{y{U0zY$zI`q zFd-jvn-9P9_-`GS>-3Rm9;+t1!vAD|6#IJm-I#C_?jl^~>-?V*mia$e$o~{!zB}6| za~^MiIUiq^|HYzaoow_miVX4|7Y+t-rRh~>f^|&>F3=<+OjiM{@-Ws Bupj^c diff --git a/utils/__pycache__/api_reader.cpython-312.pyc b/utils/__pycache__/api_reader.cpython-312.pyc index 7fbedccd16b855fa437f38a06fc9a8e0fd4691ed..7a7265dd6878edb9c860ffa9da54ccb2ec0e74b9 100644 GIT binary patch delta 94 zcmZ45&$zOmk@qw&FBbz4m|mApySb6qijmQ6vIpZF6L5@+{C=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%9N4YmD1f zP}5wqQmPQyn|EH^CDd%S8L*28bhU{W@ZB|w=aOcTDGIsKX3&|5+iyA z;M%>zWwISDXXM=+Nm+&*#32T6L4dm>i8R06c!YT^1|Mgj8S*z6`wD}vGWZe$nxnOf zFY%ivY#f9A3=T24SLd;cHVSMSe(piuUOX{B8(1Yj7!HE`LqRDR56Zy=Qep6(;8gIo z;JzR%7A5OXjmwwuQkfNz8HzYm4XLj zjlZ#3V6gd;c_|~~kIf#I{!H9|fQA-* z0TJIeFS5>Il={HL!0@Ai;Q^m$e_m(ajF9=UGh;94I9=v*-mGr>l#TK4WL}q3j6#!d zxWqDk+id3gn5F(NNIMTB1H&!0jKt!MjEthMK#@!VJ_d%D5+FG~pqwUG5jTjP1|s-@ z0!0EKLJ&jS(@BMLLdPVkbo$N*bL%|fmjkCLJ~x9gSAV6n9`dU ldo}Zl%7NI*Ai@wtSbzwd&DIgzjEn-4-6Pe3ftMfY4gj+JTFL+b delta 293 zcmX@PnQ_}@M&8rByj%=Gu(UxWO=%^Yx1}({mGbQxc0alJXOa zQZ@@S?Kb7O#paZgpPXI1`H6WcBjeA_QI`Hp+<$>a6nzB|-#2fu&S7MHKUvXMc(Sjo z_+}s5%WRDQCM&p{VicbI+9j6p`({tq$1M8)K&p8e85nM{WdLo+$SC>-6v-6eV_Haf8@t43iVQ#9c&yLPgU+0!$!Q6Og6JT_gk&5CsW{fr!l@t~iJ#2_mFG vgfNJZ1`#rww|O=5ipqo7Dj>oLL|B3d+s%Fv+>DHZlcOTl8C@nfMY;n3aVbmw diff --git a/utils/api_reader.py b/utils/api_reader.py index fb454bb1..94561926 100644 --- a/utils/api_reader.py +++ b/utils/api_reader.py @@ -85,10 +85,9 @@ def update_data(self): ### BLOCK STATS ### - url = '{}/{}'.format(self.base_api, 'Blocks') + url = '{}/{}'.format(self.base_api, 'blocks?pageSize=5000') block_data = self.get_api_data(url) block_df = DataFrame(block_data) - print(block_df.columns) try: block_df['Time Found'] = to_datetime(block_df['created']) @@ -171,7 +170,6 @@ def get_latest_worker_samples(self, totals=False): ''' df = self.miner_latest_samples - print(df) total_ls = [] work_ls = [] @@ -179,13 +177,10 @@ def get_latest_worker_samples(self, totals=False): for miner in df.miner.unique(): temp = df[df.miner == miner] - print(temp.columns) temp_block = block_df[block_df.miner == miner] try: temp_latest = max(temp_block['Time Found']) - print('latest') except ValueError: - print('value error') temp_latest = min(block_df['Time Found']) if not isinstance(temp_latest, str): @@ -218,7 +213,6 @@ def get_total_hash_data(self): for date in self.miner_sample_df.created.unique(): temp = self.miner_sample_df[self.miner_sample_df.created == date] - print(temp.hashrate.sum()) total_hash.append([date, temp.hashrate.sum() / 1e3]) # DF FOR PLOTTING TOTAL HASH ON FRONT PAGE diff --git a/utils/dash_utils.py b/utils/dash_utils.py index 1c5b3b78..547cbaa2 100644 --- a/utils/dash_utils.py +++ b/utils/dash_utils.py @@ -1,4 +1,3 @@ -from utils.reader import SigmaWalletReader, PriceReader from dash import Dash, html, dash_table, dcc import dash_bootstrap_components as dbc diff --git a/utils/reader.py b/utils/reader.py deleted file mode 100644 index eaab04b3..00000000 --- a/utils/reader.py +++ /dev/null @@ -1,484 +0,0 @@ -import requests -from hydra import compose, initialize -from omegaconf import DictConfig, OmegaConf -from pandas import DataFrame, concat, to_datetime -from pycoingecko import CoinGeckoAPI -from datetime import datetime -from hydra.core.global_hydra import GlobalHydra -import pytz - - -class PriceReader: - def __init__(self): - self.cg = CoinGeckoAPI() - - def get(self, debug=False): - # Fetch current price of Bitcoin (BTC) and Ergo (ERG) in USD - if debug: - return 10, 10 - else: - prices = self.cg.get_price(ids=['bitcoin', 'ergo'], vs_currencies='usd') - btc_price = prices['bitcoin']['usd'] - erg_price = prices['ergo']['usd'] - return btc_price, erg_price - -class SigmaWalletReader: - # def __init__(self, api, token_id, token_ls_url='https://api.ergo.aap.cornell.edu/api/v1/tokens/'): - # self.api = api - # self.token_id = token_id - # self.token_ls = token_ls_url - - def __init__(self, config_path: str): - self.block_reward = 30 #need to calc this from emissions.csv - self.config_path = config_path - try: - initialize(config_path, self.config_path, version_base=None) - except ValueError: - GlobalHydra.instance().clear() - initialize(config_path, self.config_path, version_base=None) - cfg = compose(config_name='conf') - - self.api = cfg.default_values.url - self.token_id = cfg.user_defined.token_id - self.token_ls = cfg.default_values.token_ls - self.base_api = cfg.default_values.base_api - - def get_miner_ls(self): - data = self.get_api_data('{}/{}'.format(self.base_api, 'miners')) - miner_ls = [] - for sample in data: - miner_ls.append(sample['miner']) - - return miner_ls - - def get_front_page_data(self): - pool = self.get_api_data(self.base_api)['pool'] - - payment_data = pool['paymentProcessing'] # dict - - port_data = pool['ports'] - - ls = [] - for port in port_data: - temp = port_data[port] - if 'pikes_peak' in temp['name']: - high_or_low = 'Greater Than 10GH/s' - else: - high_or_low = 'Lower Than 10GH/s' - ls.append([temp['name'], port, high_or_low, temp['tls']]) - port_df = DataFrame(ls, columns=['Name', 'Port', 'Hashrate Threshold', 'TLS']) - - pool_fee = pool['poolFeePercent'] - pool_stats = pool['poolStats'] # dict - net_stats = pool['networkStats'] # dict - - total_paid = pool['totalPaid'] - total_blocks = pool['totalBlocks'] - last_block_found = pool['lastPoolBlockTime'] - - format_string = '%Y-%m-%dT%H:%M:%S.%fZ' - - date_time_obj = datetime.strptime(last_block_found, format_string) - last_block_found = date_time_obj.strftime('%A, %B %d, %Y at %I:%M:%S %p') - - pool_effort = pool['poolEffort'] - - data = {'port_df': port_df, - 'fee': pool_fee, - 'paid': total_paid, - 'blocks': total_blocks, - 'last_block_found': last_block_found, - 'pool_effort': pool_effort} - - for key in payment_data.keys(): - data[key] = payment_data[key] - - for key in pool_stats.keys(): - data[key] = pool_stats[key] - - for key in net_stats.keys(): - data[key] = net_stats[key] - - data['poolHashrate'] = data['poolHashrate'] / 1e9 # GigaHash/Second - data['networkHashrate'] = data['networkHashrate'] / 1e12 # Terra Hash/Second - data['networkDifficulty'] = data['networkDifficulty'] / 1e15 # Peta - - return data - - def get_main_page_metrics(self, wallet, debug=False): - ''' btc_price, erg_price, your_total_hash, pool_hash, network_hashrate, avg_block_effort, network_difficulty ''' - price_reader = PriceReader() - btc, erg = price_reader.get(debug) - _, performance_df = self.get_mining_stats(wallet) - _, _, effort_df = self.get_block_stats(wallet) - data = self.get_front_page_data() - pool_hash = data['poolHashrate'] - net_hash = data['networkHashrate'] - net_diff = data['networkDifficulty'] - your_total_hash = round(performance_df[performance_df['Worker'] == 'Totals']['Hashrate [Mh/s]'].iloc[0], 5) - avg_block_effort = round(effort_df[effort_df['Mining Stats'] == 'Average Block Effort']['Values'].iloc[0], 5) - return btc, erg, your_total_hash, pool_hash, net_hash, avg_block_effort, net_diff - - def get_api_data(self, api_url): - try: - # Send a GET request to the API - response = requests.get(api_url) - - # Check if the request was successful (status code 200) - if response.status_code == 200: - # Parse the response as JSON (assuming the API returns JSON data) - data = response.json() - return data - else: - print(f"Failed to retrieve data: Status code {response.status_code}") - return None - - except requests.exceptions.RequestException as e: - # Handle any exceptions that occur during the request - print(f"An error occurred: {e}") - return None - - def get_estimated_payments(self, wallet): - url = '{}/{}'.format(self.base_api, 'miners') - miner_data = self.get_api_data(url) - - miners = {} - for sample in miner_data: - miners[sample['miner']] = 0 - - for key in miners.keys(): - unique_miner_url = '{}/{}'.format(url, key) - sample_miner = self.get_api_data(unique_miner_url) - miners[key] = sample_miner['pendingShares'] - - total = sum(miners.values()) - rewards = {key: (value / total) * self.block_reward for key, value in miners.items()} - reward_df = DataFrame(list(rewards.items()), columns=['miner', 'reward']) - reward_df['my_wallet'] = reward_df['miner'].apply(lambda address: address == wallet) - - return reward_df - - def get_all_miner_data(self, my_wallet): - # - wallets = self.get_miner_ls() - data = [] - - for wallet in wallets: - temp = self.get_miner_samples(wallet) - temp['miner'] = wallet - latest = max(temp['created']) - latest_df = temp[temp.created == latest] - data.append(latest_df) - df = concat(data) - - df['hashrate'] = df['hashrate'] / 1e6 # Mh/s - - total_hash = df['hashrate'].sum() - df['Percentage'] = (df['hashrate'] / total_hash) * 100 - df['ProjectedReward'] = (df['Percentage'] / 100) * self.block_reward - df['my_wallet'] = df['miner'].apply(lambda address: address == my_wallet) - df['miner'] = df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - return df - - def get_total_hash(self): - miners = self.get_miner_ls() - data = [] - for miner in miners: - temp = self.get_miner_samples(miner) - data.append(temp) - - df = concat(data) - ls = [] - for date in df.created.unique(): - temp = df[df.created == date] - ls.append([date, temp.hashrate.sum() / 1e9]) - - return DataFrame(ls, columns=['Date', 'Hashrate']) - - def get_miner_samples(self, wallet): - # - url = '{}/{}/{}'.format(self.base_api, 'miners', wallet) - sample_data = self.get_api_data(url) - try: - samples = sample_data['performanceSamples'] - except TypeError: - return DataFrame({'created': [0], 'hashrate': [0], 'worker': ['not loaded']}) - - flattened_data = [] - - for entry in samples: - created_time = entry['created'] - - for worker_name, metrics in entry['workers'].items(): - - flat_entry = { - 'created': created_time, - 'worker': worker_name, - 'hashrate': metrics['hashrate'], - 'sharesPerSecond': metrics['sharesPerSecond'] - } - - flattened_data.append(flat_entry) - df = DataFrame(flattened_data) - - if df.empty: - df = DataFrame({'created': [0], 'hashrate': [0], 'worker': ['not loaded']}) - - return df - - - def get_mining_stats(self, wallet): - # - url = '{}/{}/{}'.format(self.base_api, 'miners', wallet) - mining_data = self.get_api_data(url) - # WALLET NOT ADDED EXCEPTIONS - try: - mining_dict = {'pendingShares': mining_data['pendingShares'], - 'pendingBalance': mining_data['pendingBalance'], - 'totalPaid': mining_data['totalPaid'], - 'todayPaid': mining_data['todayPaid']} - except: - mining_dict = {'pendingShares': 0, - 'pendingBalance': 0, - 'totalPaid': 0, - 'todayPaid': 0} - - # MINERS NOT PAID YET EXCEPTIONS - try: - mining_dict['lastPayment'] = mining_data['lastPayment'] - mining_dict['lastPaymentLink'] = mining_data['lastPaymentLink'] - - except KeyError: - mining_dict['lastPayment'] = 0 - mining_dict['lastPaymentLink'] = 'Keep Mining!' - - except TypeError: - mining_dict['lastPayment'] = 0 - mining_dict['lastPaymentLink'] = 'Keep Mining!' - - # EXCEPTION LOGIC FOR USERS TO INPUT THEIR ADDRESS - try: - performance = mining_data['performance'] - performance_df = DataFrame(performance['workers']).T # Transpose to get workers as rows - performance_df.reset_index(inplace=True) # Reset index to get workers as a column - performance_df.columns = ['Worker', 'Hashrate [Mh/s]', 'SharesPerSecond'] # Rename columns - performance_df['Hashrate [Mh/s]'] = performance_df['Hashrate [Mh/s]'] / 1e6 # MH/s - except: - print('NO VALID WALLET ENTERED'.format(wallet)) - - performance = 'PLEASE ENTER YOUR MINING WALLET ADDRESS' - performance_df = DataFrame() - performance_df['Hashrate [Mh/s]'] = 0 - performance_df['SharesPerSecond'] = 1e-6 - - total_hash = sum(performance_df['Hashrate [Mh/s]']) - total_shares = sum(performance_df['SharesPerSecond']) - - temp = DataFrame({'Worker': 'Totals', 'Hashrate [Mh/s]': total_hash, 'SharesPerSecond': total_shares}, index=[0]) - - performance_df = concat([performance_df, temp]) - - mining_df = DataFrame.from_dict(mining_dict, orient='index', columns=['Value']) - mining_df.reset_index(inplace=True) - mining_df.columns = ['Mining Stats', 'Values'] - - return mining_df, performance_df - - def get_block_stats(self, wallet): - # - url = '{}/{}'.format(self.base_api, 'Blocks') - block_data = self.get_api_data(url) - miners = {} - blocks = {} - for block in block_data: - miner = block['miner'] - block_height = block['blockHeight'] - - try: - miners[miner] += 1 - except KeyError: - miners[miner] = 1 - try: - blocks[block_height] = block['effort'] - except KeyError: - blocks[block_height] = 0 - - try: - average_effort = {'Average Block Effort': sum(blocks.values()) / len(blocks)} - except ZeroDivisionError: - average_effort = {'Average Block Effort': 0} - - block_df = DataFrame(block_data) - - miner_df = DataFrame.from_dict(miners, orient='index', columns=['Value']) - miner_df.reset_index(inplace=True) - miner_df.columns = ['miner', 'Number of Blocks Found'] - - try: - block_df['my_wallet'] = block_df['miner'].apply(lambda address: address == wallet) - miner_df['my_wallet'] = miner_df['miner'].apply(lambda address: address == wallet) - - except ValueError: - print('my wallet_value errr') - block_df['my_wallet'] = 'NOT ENTERED' - miner_df['my_wallet'] = 'NOT ENTERED' - - except KeyError: - block_df['my_wallet'] = 'NONE' - miner_df['my_wallet'] = 'NONE' - - miner_df['miner'] = miner_df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - - - effort_df = DataFrame.from_dict(average_effort, orient='index', columns=['Values']) - effort_df.reset_index(inplace=True) - effort_df.columns = ['Mining Stats', 'Values'] - - try: - block_df['Time Found'] = to_datetime(block_df['created']) - block_df['Time Found'] = block_df['Time Found'].dt.strftime('%Y-%m-%d %H:%M:%S') - except KeyError: - block_df['Time Found'] = 'Not Found Yet' - - try: - block_df['miner'] = block_df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - block_df['effort'] = round(block_df['effort'], 5) - except KeyError: - block_df['miner'] = 'NONE' - block_df['effort'] = 'NONE' - block_df['networkDifficulty'] = 0 - self.latest_block = max(block_df['Time Found']) - - block_df = block_df.filter(['Time Found', 'blockHeight', 'effort', 'status', 'confirmationProgress', 'reward', - 'miner', 'networkDifficulty', 'my_wallet']) - - return block_df - - def calculate_mining_effort(self, network_difficulty, network_hashrate, hashrate, last_block_timestamp): - """ - Calculate the mining effort for the pool to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated mining effort for the pool. - """ - - network_difficulty = network_difficulty * 1e15 - network_hashratev = network_hashrate * 1e12 - hashrate = hashrate * 1e6 - - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty# This is a simplification - - # Total hashes by the network in the time since last block - total_network_hashes = network_hashrate * time_since_last_block - - # Pool's share of the total network hashes - pool_share_of_hashes = (hashrate / network_hashrate ) * total_network_hashes - - # Effort is the pool's share of hashes divided by the number of hashes to find a block - effort = pool_share_of_hashes / hashes_to_find_block * 100 - - return round(effort, 3) - - def calculate_time_to_find_block(self, network_difficulty, network_hashrate, hashrate, last_block_timestamp): - """ - Calculate the time to find a block on Ergo blockchain based on the given timestamp. - - :param network_difficulty: The current difficulty of the Ergo network. - :param network_hashrate: The total hash rate of the Ergo network (in hashes per second). - :param pool_hashrate: The hash rate of the mining pool (in hashes per second). - :param last_block_timestamp: Timestamp of the last block found in ISO 8601 format. - :return: The estimated time to find a block for the pool. - """ - - network_difficulty = network_difficulty * 1e15 - network_hashrate = network_hashrate * 1e12 - hashrate = hashrate * 1e6 - - # Parse the last block timestamp - time_format = '%Y-%m-%d %H:%M:%S' - last_block_time = datetime.strptime(last_block_timestamp, time_format) - last_block_time = last_block_time.replace(tzinfo=pytz.utc) # Assume the timestamp is in UTC - - # Get the current time in UTC - now = datetime.now(pytz.utc) - - # Calculate the time difference in seconds - time_since_last_block = (now - last_block_time).total_seconds() - - # Hashes to find a block at current difficulty - hashes_to_find_block = network_difficulty # This is a simplification - - # Calculate the time to find a block - print(hashrate, 'hashhh', hashes_to_find_block) - try: - time_to_find_block = hashes_to_find_block / hashrate - except ZeroDivisionError: - time_to_find_block = 1 - - return round(time_to_find_block / 3600 / 24, 3) - - def get_pool_stats(self, wallet): - # - data = self.get_api_data(self.base_api) - pool_data = data['pool']['poolStats'] - net_data = data['pool']['networkStats'] - net_data['networkHashrate'] = net_data['networkHashrate'] / 1e12 - net_data['networkHashrate [Th/s]'] = net_data.pop('networkHashrate') - - net_data['networkDifficulty'] = net_data['networkDifficulty'] / 1e15 - net_data['networkDifficulty [Peta]'] = net_data.pop('networkDifficulty') - - pool_data['poolHashrate'] = pool_data['poolHashrate'] / 1e9 - pool_data['poolHashrate [Gh/s]'] = pool_data.pop('poolHashrate') - - top_miner_data = data['pool']['topMiners'] - - pool_df = DataFrame(list(pool_data.items()), columns=['Key', 'Value']) - net_df = DataFrame(list(net_data.items()), columns=['Key', 'Value']) - - df = concat([pool_df, net_df], ignore_index=True) - df.columns = ['Pool Stats', 'Values'] - - top_miner_df = DataFrame(top_miner_data) - top_miner_df['my_wallet'] = top_miner_df['miner'].apply(lambda address: address == wallet) - top_miner_df['miner'] = top_miner_df['miner'].apply(lambda x: f"{x[:5]}...{x[-5:]}" if len(x) > 10 else x) - top_miner_df['hashrate'] = top_miner_df['hashrate'] / 1e6 # Mh/s - - total_hash = top_miner_df['hashrate'].sum() - top_miner_df['Percentage'] = (top_miner_df['hashrate'] / total_hash) * 100 - top_miner_df['ProjectedReward'] = (top_miner_df['Percentage'] / 100) * self.block_reward - return df, top_miner_df - - def find_token_in_wallet(self, wallet): - url = '{}/{}'.format(self.api, wallet) - wallet_data = self.get_api_data(url) - - wallet_contents = wallet_data['items'] - for contents in wallet_contents: - if contents['assets']: - for items in contents['assets']: - token_id = items['tokenId'] - if token_id == self.token_id: - return True - - def get_token_description(self): - url = '{}/{}'.format(self.token_ls, self.token_id) - data = self.get_api_data(url) - - token_description = data['description'] - return token_description From 0e1e706e0f7785dcd1a5d735b9f6ce4e58758405 Mon Sep 17 00:00:00 2001 From: Marc Mailloux Date: Wed, 17 Apr 2024 09:00:16 -0600 Subject: [PATCH 2/2] removing pycache --- .gitignore | 1 + __pycache__/locustfile.cpython-312.pyc | Bin 2122 -> 0 bytes layouts/__pycache__/front_page.cpython-310.pyc | Bin 11738 -> 0 bytes layouts/__pycache__/front_page.cpython-312.pyc | Bin 18115 -> 0 bytes layouts/__pycache__/front_page.cpython-36.pyc | Bin 11828 -> 0 bytes layouts/__pycache__/front_page.cpython-39.pyc | Bin 11822 -> 0 bytes .../__pycache__/front_page_1.cpython-310.pyc | Bin 11717 -> 0 bytes .../__pycache__/front_page_1.cpython-312.pyc | Bin 17414 -> 0 bytes layouts/__pycache__/front_page_1.cpython-39.pyc | Bin 11074 -> 0 bytes layouts/__pycache__/main_page.cpython-312.pyc | Bin 12846 -> 0 bytes layouts/__pycache__/main_page.cpython-36.pyc | Bin 8038 -> 0 bytes layouts/__pycache__/main_page.cpython-39.pyc | Bin 7968 -> 0 bytes layouts/__pycache__/mining_page.cpython-310.pyc | Bin 9707 -> 0 bytes layouts/__pycache__/mining_page.cpython-312.pyc | Bin 19732 -> 0 bytes layouts/__pycache__/mining_page.cpython-39.pyc | Bin 11553 -> 0 bytes .../__pycache__/mining_page_1.cpython-310.pyc | Bin 9795 -> 0 bytes .../__pycache__/mining_page_1.cpython-312.pyc | Bin 16950 -> 0 bytes .../__pycache__/mining_page_1.cpython-39.pyc | Bin 11555 -> 0 bytes utils/__pycache__/api_reader.cpython-310.pyc | Bin 10873 -> 0 bytes utils/__pycache__/api_reader.cpython-312.pyc | Bin 18345 -> 0 bytes utils/__pycache__/api_reader.cpython-39.pyc | Bin 17776 -> 0 bytes utils/__pycache__/dash_utils.cpython-310.pyc | Bin 4203 -> 0 bytes utils/__pycache__/dash_utils.cpython-312.pyc | Bin 5793 -> 0 bytes utils/__pycache__/dash_utils.cpython-36.pyc | Bin 4166 -> 0 bytes utils/__pycache__/dash_utils.cpython-39.pyc | Bin 4172 -> 0 bytes utils/__pycache__/reader.cpython-310.pyc | Bin 13963 -> 0 bytes utils/__pycache__/reader.cpython-312.pyc | Bin 22985 -> 0 bytes utils/__pycache__/reader.cpython-36.pyc | Bin 14284 -> 0 bytes utils/__pycache__/reader.cpython-39.pyc | Bin 14111 -> 0 bytes 29 files changed, 1 insertion(+) delete mode 100644 __pycache__/locustfile.cpython-312.pyc delete mode 100644 layouts/__pycache__/front_page.cpython-310.pyc delete mode 100644 layouts/__pycache__/front_page.cpython-312.pyc delete mode 100644 layouts/__pycache__/front_page.cpython-36.pyc delete mode 100644 layouts/__pycache__/front_page.cpython-39.pyc delete mode 100644 layouts/__pycache__/front_page_1.cpython-310.pyc delete mode 100644 layouts/__pycache__/front_page_1.cpython-312.pyc delete mode 100644 layouts/__pycache__/front_page_1.cpython-39.pyc delete mode 100644 layouts/__pycache__/main_page.cpython-312.pyc delete mode 100644 layouts/__pycache__/main_page.cpython-36.pyc delete mode 100644 layouts/__pycache__/main_page.cpython-39.pyc delete mode 100644 layouts/__pycache__/mining_page.cpython-310.pyc delete mode 100644 layouts/__pycache__/mining_page.cpython-312.pyc delete mode 100644 layouts/__pycache__/mining_page.cpython-39.pyc delete mode 100644 layouts/__pycache__/mining_page_1.cpython-310.pyc delete mode 100644 layouts/__pycache__/mining_page_1.cpython-312.pyc delete mode 100644 layouts/__pycache__/mining_page_1.cpython-39.pyc delete mode 100644 utils/__pycache__/api_reader.cpython-310.pyc delete mode 100644 utils/__pycache__/api_reader.cpython-312.pyc delete mode 100644 utils/__pycache__/api_reader.cpython-39.pyc delete mode 100644 utils/__pycache__/dash_utils.cpython-310.pyc delete mode 100644 utils/__pycache__/dash_utils.cpython-312.pyc delete mode 100644 utils/__pycache__/dash_utils.cpython-36.pyc delete mode 100644 utils/__pycache__/dash_utils.cpython-39.pyc delete mode 100644 utils/__pycache__/reader.cpython-310.pyc delete mode 100644 utils/__pycache__/reader.cpython-312.pyc delete mode 100644 utils/__pycache__/reader.cpython-36.pyc delete mode 100644 utils/__pycache__/reader.cpython-39.pyc diff --git a/.gitignore b/.gitignore index 06c8305f..6be23c5d 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ *flask_session *_files/ *venv +**__pycache__/ diff --git a/__pycache__/locustfile.cpython-312.pyc b/__pycache__/locustfile.cpython-312.pyc deleted file mode 100644 index 86feea2969256d600d091ee8d859c0675f3da064..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2122 zcmZ`)%}*Og6rb5$FB@zV2(*+6lC7GAIu*7MQbY4us;EsH3H4J*zHArI01LZbcV;aF z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1Ez=roph^(L-+@KewH0+}A^I7vi80tvj1Ie&+cVX?iy1 zm;>J$#*bwyYrimkP84bQ^WiP(NXyYz)R9`pme$c)wSASQy6H(8e10T;5wyQsGo;z3 zsPmf3_$_p4uAq-n)0AfW8r@Lo)NI|WQ6}CBooBoDh4GmUy-{V{0P2|VQ?1%_lmM<6*cc{@*|#Tlo2)3!oL4H=a;rDEK3g z{@QdJd==;Y+!?+RsKbAha0x;<7ozFEqO$&)YX1wW{jaD)e@z|#6;<(f8j2p*{v8xl zLudiwzoHKOiYosfRM9VU%YJw1jumeCnse^xU*sOVWBtygqv5819;kI9dq3R%NE9D< znPtq;+_8W&nUa`OlpyJe{L(~j$;;yW%BA*~MqM!^6>M3lYKL^ZFR{P+ zX+2!xc&Vjxo%Ee7;52XF!(u6ixs&ysPDfAC-&x<&(3RgsbzTjv*&5eVI_q-eYi()5 zVq32H*nZc3um5S+9}oWF;6_`2tgT;a9ay&v-s$>fe)-QU?sWZh@Rzy+4~2DIbwX$S Y*~ssVJS@C3@)x=TTV_gEM&$l~0d$?srT_o{ diff --git a/layouts/__pycache__/front_page.cpython-36.pyc b/layouts/__pycache__/front_page.cpython-36.pyc deleted file mode 100644 index 77f16ca0cd28eb5ad51b8e8c78a05f3c3601580d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11828 zcmcgy+jAS&dB#haw?5@!J}w7|k= z7bdv|nrZ2_c_=68Tc_c4+L^xey$_lGDf`&=q3TShGwEBN`uomVf|MOksZ6KX!P#^D z&Ue0Z&Uf9Lqoak7o|YSzHZqxi%^dp`kpBVxVWea-EW;E(W7AvpGi}9I+N!O#HCt=z zw%#^uLy>(5iHDML3ws&+0?XQ#J8i$s zaxDK<#=hvDa!<1Y8)3x*-5wXEQC32kp0R_heTkLXIGaeHNxY}nse``k=3#V#Be_El!Fw>`xkV;9*a%vola*%iFsVOQBZcwciX z?AiC|5|dC==H z*{7m#6=YeeYeXIV=uL<90si3?x7K)P1Tk`wG*T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pyc b/layouts/__pycache__/front_page_1.cpython-312.pyc deleted file mode 100644 index ff8a06ab1e082d0da45a729e1b20fbc1d75cc129..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17414 zcmch8X>1f(nqWlUnNHsqHU`26-~`gQ4Y*uT#x}kWY;!mZNYeSj=`?v&M7V6S?1s^l z)Mk5jC^S8S(l9Ej)lz}*s2FLa_U`_%=Fiq_&uSyfo+UfltwuAo(z4QOO=0cqveNc` z-;0dQgf)ffot-qic=3+!eeZkkeb@WqmzkM127b*?_D%iQ5r+8(e9?Zi23}tLXO>~^ zFoYp&fN|kd7hr;{iw){rx}e^r4;oyCpwVSy)ix%V8QSOrmY~&T4cc5bT5bqr1nn+6 z%^L%m!7Nu+Fx!N=PYRM0VfPyY>T=B2osmd&u5< zM%Mwdk8pn0l}*ZF#2iuq=|NHnX*KU4RadJSMi>DcnVE5oz^Nzi;LS7VQtw)B=7N?> zJ$>x*{zp3X-Q@&`)!M9ir@KaL2jvHO=Ob7-{ILx0oN=r9^pqS}KA38AjlIS?s-Izl zA%{^hOiRIlq9c!y5O9rOEwp7WkSfR{#j58(wR zV?^+KdG*D?D%MVqwb|$SX^(5?!HT9gYqUc&GgV zBJd%Hg;HA4cltjTa-fBx?+yAC(^OapdL$tiOAKQXPe{mztV6FD=|U?8Tu{aMu_rLg zi?}Kr$Gz;Yoel^2+PP^@fETAd!qwW&uy;1dhX7p>cWuZsD>;My5a8vEgu?;ntiLwk zxfY&<22(;fB)KEFHS234*OcPK&Qv!R-9M9ou=lC}N1G{t|015S8_Y&V_N`+#kFA#; z+9=p{r{{Lh{oPN>8)M~-kGs~&Th~vGuNR!fn%>*JcgbUZ)fYQ7v|cc*74eT}*SpWh z4qsR=nAkMyTRvpB7`^=>yUFN{7ugpu1Q4JBNo(@LM0mkrP_k3|wF5V~PzJ4p-Pkm1 zW>%E^Q`b6RGSFNxHqgF?dVt_C3rDaawpL8jyx%u1(O!ZRORPA@_JH3PQp^b`im|?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|1$pY@ zc=LPlqwmL$pNzM)KermMvxnd=+i`ePZ*DuV#hCXW+|*k;*$TLWF0b6$l^6)&Re#n0 zWxrh4CHJ`j#>RWy@rGmZ#uM@SWAUce_%RBy{@C+;+cXP+YzW9s0oegi8N*e5G5`7e zchyI}wmh_K9I5-d`(byy@nrn?X#8mVYKz>`w`DdsYamddsdc6Cv2!ca>^QWQ!#JF3 zhuW_P9uCACJD#5Ck;f)tO|JNf)AAY2fdBh=0|e*8tUlT=I&~05}Ysy`^%^d}3<%JML$zriHz_FYwh&=o+Q4&%!J?J80ZHShAOvDCmg@dTjh_Y=S&c0aBx8?{;I%mN*Uf!VnY=cdOP@!^7ia6XfGV%EZq%TvM{SqEsy7x#IuW^XIt`gH!zq6%ZuXqCGmpNc;2pf;cmDV zjb{}=nYbS`l`HyeteC=UY0E1mMu z?)aX{$JG!9{#?&yyVx5U_<7Q cW!zx?@z5U(-7UB=^mm56n^wk9N{`6@0Sb^e6aWAK diff --git a/layouts/__pycache__/front_page_1.cpython-39.pyc b/layouts/__pycache__/front_page_1.cpython-39.pyc deleted file mode 100644 index a471f6e28d4c66a156a65e317438a6e59443d9b5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11074 zcmcgyTWlLwdgfd>98wf@mt*HPz9nXC(voZ^8?Td%Z;G@lOO7NbyKEQCh-XNSJmhfC z3?qq=n%#AZZMzlHqD4_)_26ua7AgANZWri7(LVO2-2z2V+n4sq`?3WJG+8BH_xsO` zC@X1DIw;Bk&z$Rj{_~&z{I@f9e}5){-yhr_s{U*~k@$BiJp7~9SMU$kl|+IinBpZ$ z^j5t@Ln$c@wWKz*lGe~mdLvm%Dp4P!ltLfPGaKnrx{)bmWWDb7HL|6w%qPA6My`}= z43q{MgQda7P-&K znKvR_l!TMHlPEpSQYFh7FCAqjOTU{a9dpK@jv2BXjHsd)ygkPwZ%=lYlbLo< zqVud%xT9blh1Ij{Id*y*d8RBS@@MYRp3LWyLa&DnPiU-C5y{z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?}I- zSwleEZCW>QH(GNjnB4Q`P8F@$rZwXSAq8D543+1>v9RQepIUFvK+hHBvArla>=EfR z=Qi8xw8A&sCgO@g&y!-qt}~Zpj$;*rx&^nxks^mG_JouL@$K+4M69q5j;fFg=J}qi z?s=++Xc4P|@-PA9CG|tptF}E)9+x#YtVgoYuM#IC1l{vAZ@&3v&wWWjy!1b?XU_oM zxI8y^efgzJB;?C$@}rD$Y!|&;eC_LnX}ejt>a|yT23R}`x=LMZ6$-Xj^R3IbmKWx} z@wJ5|$Z~meZ=E2tQE0=Ov`$1QSSMcTc@8LEZ1OKzC%$48oNrm@r>t*&*sVTlWIPJJ zf`}|k@UAIOpXXG)HX=yUMWOoqnEd2`A45L6981HP2yGIge3UBb##NZJ@twL*XC~#h z3H&xS&QPLL593PYxnv^`CjNlRycS;`iR7!?Zq@k^4KQec{Pb&?0+FIGita?;F_|}T zyCCnIWavZ&QDh>6D48h61Q{0o6QBeFNkTb-YcxFSusW;_Bg$hSY8uB^KQSNRqAW`h zpl-xyN#}_GdT$`{6 zf@tdp+o9_PMZ4w3m#Cbgyqr8~e0Ks%&Wo#FbxJ;> z=h%6a^=2?kwf|5^P$ln*L-5oIB<($AdZRHzp0vr`3~+9-bp-{!6h;HRQYe1bwHQ^ diff --git a/layouts/__pycache__/main_page.cpython-312.pyc b/layouts/__pycache__/main_page.cpython-312.pyc deleted file mode 100644 index f0231d78078e12dbd713802d6e114ddafee43a64..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12846 zcmcI~Yfv0nc4lV1Ur;=&pm->GNKoR9goNHgfCLgkG$5%d(W)*glcJzr%1Q)OSM|`b z-e`I~5!18b*r9hc(RgBaO|Rq_9QLm9Mz2HRUy7Kqoi)Xna+;2oy}fp{|18}i9J}m~ z*>i4IR-tZ2({0Zt)XjU(z31F>&wb=Q-@QN0%QI2%B!8JV-E)Sb{s$(M$C8P>_%oWK zen7DlO9!YR?V^J!mx{);DxeN(T$-TPr48y_Izm$i^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F-}# zz}p|TebBbqc{};qx+5(mTN@MaU z^M7J_oV;)#1UrMtcP4iX`J$CsJDxJMKy>Bp)y0&dF+*%j8JbA6X01DAXnrYwQ}8Df0(PRdY^EQ!_Wl;J4JZd?bECrGqmy)0$u+%2~hpWJg$CFNpy z%X%VJd_gR_xKm_b)vm@;MaRX$rWaNDx|T1PBU;mo8YRX|yZ+0vuW* zaw~6maa&3@yF4yv@}XZVx9H^}xbu$kc<~i#;{yTzRBOb;!v$tCealG|Q{k`x)7TS% zZFc6abrh~tPkAL>1YBefo*lDro(m3YU;vds^U|sGf8!RLRJ3*buLMr`;i3Mzg(v26KkE3-baWj(!Y`BF1a z)7R8rgw)jAsvEd44XJPA!t}Q44lYb|T(xXoaf{Wh8s<`S)%_%xSe;J|MY18gBO=&DEv7f8U)3CW8erI?U&e=BlmWO|#IRkq@ Jje}U|{{cD+1p5F0 diff --git a/layouts/__pycache__/main_page.cpython-36.pyc b/layouts/__pycache__/main_page.cpython-36.pyc deleted file mode 100644 index 5e9fb3349a726794d717920648aa0df71bb09fc9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8038 zcmbtZOLN@Db{=3bFU*^yC{hm^df3*;;!869lx52zCF|OvXp*)h*uE2R8XSVc48{$N zNWz$Gbo0EI$-PM`RmqhrcaudH$tG3#1xaO*N;cW`CRIr#73BwH;Vhi*G{Bc6XA^>G zoIc%sy8CqZ>F=DmQZDOv3zhZjZ>LiKmOAuT0{sDA|8pgkVkxG$sg7bQ9o1A7%Bya= zqnTPKV`e&8Gb?#%H`mFV`A)$sbaYei6wP9%WR_%^=9W7Zvm)t?TkX`$nxwOC-5i3v ztUGLu$nUYuQS&&coIBPTH^)0C%oClH=EAY&b+PPp}kY&2t=v*`}Dk=NC{n}&2yu^z3rOioJx|(8TNmZ_< z?2GoL#|rAGk5lH9t*|Pq?JDLptFxh>q|6z6h7CVfzATxu=4JDW`MNo0zG1#;zGc2` zzGJ>?US%Wf80x*pM%i(Eui3A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;|gGLat;`G1@iX;0irUtT>+3QJtLbwW6B3kUD25 F{|n7#BrgB} diff --git a/layouts/__pycache__/mining_page.cpython-310.pyc b/layouts/__pycache__/mining_page.cpython-310.pyc deleted file mode 100644 index c11c49315af1b6dcb860ff10421fa3d6c1c626e3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9707 zcmbVSX^7*)AReq)_N#&|arSi{z@-LmlDOd7``H@O0hs$eA%J+I^ z4=!a_7)(u1_v`ER^y~M&_XeGj5l6xAtKT`=xPC@a{+SB9e+CNAWrotAY*a3DNbJt*^La40-nJuLH9 zaHM(^JXk@w`iOjfEPS;3aaorM9t$6@J{~?%eIk6a`efR^5`LokNtw5Ur^1=)OgLMe z4d<$Jl9mmQg~zMM!xPmL;mPXB@agK);i>8=S?2`LgwIx=MLt)3&O7d%zNJ>ru)KGs z^(i)TR$&F18$GLdqt&zCv)-9os;YR}Ev5QtR%Bz|C@bC3tLNB0HvYC!{S2F6lXyPw zon}+38vmB3vi%tGyf@yO@J@S2TQ9UOG*vdeu2tu~=e_f{RByg^(Yxf$Bab)l&9`1; z2iU=N%)+cic~=hIqn)d0Vr29@{}@}wu#;40IfP9ybNbz<*IMHl8v?QSm?*4182PjfM*HoC~a+-dslSKKzXfQ#&_ zk;h;0Z~ATF1XNM$fdFRAOMx4$iVXMO?0HcvGLaWWey1&L?lGTxb&z^Is5LsACSFWx zFNuk@PLJ23Ue`nFVLRg5s<$Sb#fulNU0kYt?&9mhY50K`twpgHiu~fm#l@GdUa2j; zzHm{P%K=s>%o{5{@!Bt3>jZ({Zk8`LFb@{vCC{<87vJdc)p@_s@aw%GUaM;)ed#ZQ zC*3;kXcDSpplm3y%2cM^(wb_lF`XGQr!$jTl)J0Hqcl{OVfNehEp@1+J+jmTJssIo zL(kj~>6vFEvZtQ*ENsv9!+MOeqU>R$J;qomBR-RdM#w;5FuWDLcE$nPOPU`oL#-`S_ zxUeySdlWU3Y(JZh$9+}OOB+*z{9U!F-Bq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$OW*rMCe84_rP?t$ zC-W%K;I->Mq6X5^OPf#TUW}#vnf=>J>C1vUk z*+w0Iga{v_VxJ8=tQUCaumUBTM^aQStA|t^3wUHU m(s8;qq9h>=2S>yPa3djy2lu{hDL-kyfD0`N>=aew`~M4S-;_N7 diff --git a/layouts/__pycache__/mining_page.cpython-312.pyc b/layouts/__pycache__/mining_page.cpython-312.pyc deleted file mode 100644 index 6eaec656e835ed357ee2cb145f617bef78653706..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19732 zcmd^nX>c1?npk(^CP9GrEfTy1QY6Jgq)v*5cuAB*le7-#fI)N<1cifYfZ`#*)}&l9 zlyS;Z)*I1TRZLGNWqPeDYf_aOO=_z~H95+Yogdu>ZNfdAjCNMZ#Hq?IEizMvGzzZ%g50TpbDX078gGY6iczRhw{=k+RNA&8t)m8%B!}iy&9XwtF>vpI-Aa`x9PnGo57oAOY^4N(!EBT z(VJn*@S1EUui0kyX4*2nS+*>1wk?~`P#eiZ#qoE0t+slS z)_WSfdu)5WjkZQ_ldXxs44!81UfW)8i><}mYHRhj+1kAAwsw-2=Go`%uysH>-PXxa z++J?~`?M?>+X2?d9heC!0!zkh#$mW&O<$2~#$3*9I|TGPxC073nu2@g{WuxhVK$S^ z;>>LJU6t(!oAWAV>tb^uJj(57^RDcsDE>U)(`>#{-qy|K%vh6LC@F3~S2pvHl)Gd+ z^J+4!q+Im9g7=}n@v`*+{i9sBLZ9oiACq$^uoQ|5V9M#%$reBBeY{ zEov9F*5c1F+sa5;<8GJNan|ASaKSOo!E(HmKFYhDoP1+7OX+T}!^PPH!9@=zWjcAz z5#;Q%ZqDwUcJRRjWYWRMA^CBfpkvYlSbp!U-^clak~t3N{quIGgJ-3JI6$r-$Snlz zlODhGij;=gN{w=EDrC|h4Enuxq$6`B<2(HxKQCoYI-FNrynoKeLfr)7aq!RpLO%`( zc%i|mknA|k)V5{>{j!Zqk}kjn0&c%g((@ea<~b*T=6H{N z%FkoP<8tnR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<0}wQi9r`QVa_lXLLFARjavcPwurayChW{wsiAzyV)U$1FLW@wiUO zi zJ&K19U{Pd6e5ya}^|Nyxu8W@s82nKIBZP3wqv>B#oqxwrG^>Uq`?e4!89;tXb$v{A z{erUog0lRas{1*W^9!ovmsG1rwf=%C`!#h)qz?U(I{Yzp_!m?~OrLQ>^QplUS@>@G z4Q;G!-wo|+8Q;l>ctolsX4wrLyeq5FM5 zJpO~@>+M5g`;gE!9I-~zj^F6}G^=EJAevQmqwm$@pQ_8211ke->V}wF_u8rNoLbJk Qaq44r*=9PWE+*3YKTNp?{Qv*} diff --git a/layouts/__pycache__/mining_page.cpython-39.pyc b/layouts/__pycache__/mining_page.cpython-39.pyc deleted file mode 100644 index 2b99cf1e7ecbeef312f311a6b51c7203a9e63933..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11553 zcmb_iX>c4#R<5h7Pj$DX)@93f`?hRL@-Z{(nelpjNIrIaXeG^hreg ztm?7Uu4W?efNenRENs9M7?73)Vjuz{xPo8&U?cbeL~t!v!mouO!u;Wk-5o7n^S!Lr zVb8?Ia&$$%%6xghe3|*Zmt}W#B^3N#xt5*(jZZ1cKTu@r&p_lX{@#~VMPUk4tBR{y zs;gO=N^z~KyM|@B5i8=Fmgz>Vs2j6lZrqBy2`k|yt)!c>Qf`;k<)*E)o3S!(*2=ow zR=3+@^~gH(YOkBKa&Dj1=k{Cu?tnGm4qAgU&8QB!+pKLe9I0-1hpk~5Hmf_VooL^z z?y~aoz1!Vm?UiZK>OObBwckBp9dHj?2Rr!>xg*wL8IDztxJRv{?x;2Dj#*=p7q5=H z$E;)SaqGBy!aCuev`)IuSdmX@K+ zX~oG{FFP+dFWyyE#nJ96)@hby-A;z}Jk+gEvR;;ZPqEIhKGu)-E6yo4a7%k%**!E?#!^|0F zWcU%y*@z~(XUZklzG+vhjz8_#%;6$A#mhw}jErPNvh3O=r{MWZRYzot+_8P9&?q~F z;)2cn4bGg+JDmPb9^am;B3IpQ)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-o*eM+Fv(*{TgRIDzQX&Ycc=ZC2Cuy+Wb9i_08!Z{S%fDOfPlO>+qWF>5{kk=!( zDUOmS^l$B?Lp(h7KhEb*u;e;9rSOrS5;lv^@f7&sKSV7eDKCCHpJgS&NYSZQ;a{T9 z*9r^a7jB&td7$=(DHNtJw^*4p9rNB3@@=m`R~LnM%Fb=k$xAgpm3MG!?ORjmGq3q- z6A((SNm?i)8R?|sze|E3r>%(79%2)8;AvtKEEBOSbiW0I8~(E6{8x$pE5wgn;&x+! zlg%w+6CKN(_fb^3>}KhsJN^pgm!g*BJS8VKC7XxHyhSh-b(@aUm`-2m$jC|;M0k>$ zkBx}AX2ft3s~Q|0vF{*JjeTgu&2Jdr)CM}Pi~lkn8F>?K3(AL_j|~IwC*;b|Kx1m+ zi3v*K^uHTl!!&=={3<_-9*9_>;9}f`LMu8pHcpxiqbG-J3x{I{!f*S$1qW9RvwRAj z9l0b@O}||A#zHSFCne=Nh{%R~`B9z>a)Z)HgE=Waj}jqGlQ$teL7^m(6cG|xpeJRxEDjqaoGpv>BA~_FF=&geMtdQ?OA-gjK zMD`LP@FTjyvYn3(`F=|HG$mkC$!;hVuz$(#kZ@N^dsa!L=9>6!vxZ^QDf+XNxkrWp zvOW3`5ngb+At9604}O-inD{yieq0ehf8)mN%n+a diff --git a/layouts/__pycache__/mining_page_1.cpython-310.pyc b/layouts/__pycache__/mining_page_1.cpython-310.pyc deleted file mode 100644 index 335888fa68f520c75cc19d73d59c51de91a8c38e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9795 zcmbVSYm6J$b)Gkek0rU(KD2t$cI=pmcUQZzEz40A$y&*BV@q4@CXVSk%q;ILcepbo zeP?KCX|e$-7nad(+w|Q=O;<%*)PMT3KwGqE^QS1#{47vh^pQT$Lj6@VK!R*yyWhDp z+?Sl7Dv7zg_uSXH_nv#sch0aqGLlj7`P;ugxjO$DMfo=>?EM%hT)-24T~!pOFx6KA zwW~`Fdbfjlis$fmOAF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im160=3bMKAkxoI!dRV}n8PO~X$LJrmMbhuIW# zc*F1E#)DISrr>qs8*|yoc>wnwHZhJ3>v1Z3@l2jWSWY?*&<$ii!~uu6RxW^a9|jW` zpu*1iArRH4IPc^Hhg*}V>&=?(9Dxii{&4vAm0MR9OVR_ElHU5X8Mivv_-z zj^V9ed0q*M=z&2cXlc$J@66trU3}wVdGcjXy6%c*B|H~9!MS?THV|7{;7MXmbnM6hc6_1hSQ$W6^~Ew z_|oCmfyG|BA5rI56oh?`;xs-rouPlf#o(;rWpKh;rlP!-!(%J&H6dlqLhUA+&+lbvTX$NRx6EYm~6zH`YdW0?~JUucz`XB6u? z>d;BW>cQjd7JWt2nosduea*VEyR3GN>MnJz%_=C@p`Ra0HuSB>72U>u1(4PK3dx~K z=kbJK;dneTZF6%A-~{7_>Z}v|5 zJ(BAshsrjGIK7-kzJ(>(I8?wmG|@OTuJCI&ibIfII^aX`&7lKA7jam&2#u^lxTzx@q+%*W;lukQCWo~ z2jOuv5{ZI8u6Hv3jWRE7D;hXkge=^@$INB~j)OB$?E-IMxD$hISR8gjNaIlF z;C5huS_D^*!7d0ylT12uv72>bvXNZ zv=N+>0Xmjmr&vtTa==P>{2G{rNis=nU9!KCZ4eHM!I26MOZCUkpC1_>8R{A29wR3J z^y5w_R!VlW#+KB1g{Pc{5KW&eb#`jl!DsJ2h2+W$@+ z7O2CYQb#_dj(kFG%jisV>W}s2#PvU{o6}@!_s?nGGJW5a2ntkH#<@596c(tON0z!d zkF-_j80O;Um8y+6*XU;(Hv7KV3ola`zm81 z_JPvzv8i@`CS`KX^<@m^w_P_}H~W`Q{PgrsPOo(I3myH*_JM>eWjH-|;$vIYd|%48 pWA4P8r$1KJ&hra>Y1N*LO8eHi@1L75nLGEPs&=i2QdN@i`agUSw1@xz diff --git a/layouts/__pycache__/mining_page_1.cpython-39.pyc b/layouts/__pycache__/mining_page_1.cpython-39.pyc deleted file mode 100644 index 57fafe9dfc8789a7f1bea4041f03912a64d69ea6..0000000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^Ns$E0MC2mfZ^7V(zw8+Q8pZ!U#fQ#wtGUR@<`$8uu4T^qDJWfbbM)CA zf0Oc)_yaab3Ii2t5DaXfgxRRjUa_>3$sP28v+9 zV~Q;N>r_5TNU*kydYg1xE5cod4?=W>UfCwI$zN;NOBEn!iE$*_8KLsM-STD9mtteS zid)nzyjE_A_yRnkw~F$^LcRlq_$ZN`R2*uHG@he~T|{;h*+YcDkLU@?c0W7h`zYZv zlz>SkyP;Ub{w2Rd!d)%xS!I!!Z{f?$I)+WB=vOIoM)CmJE`5p!FSyl|kV)!?1ZlV} z!bP3!is+fESLbHuu1(Hxe1c0pdubYoZ2?wW;8;Y#w^-}YkFJedb$sSXUqfwK4U^PY zxg;W|oCa&v?9-@FaVaXTPN^e+ssvaGvStBvvoeOD9eEM))=Vq}JWotB@`3V!qD9_{ KAvG%@?SBLD71Oo= diff --git a/utils/__pycache__/api_reader.cpython-310.pyc b/utils/__pycache__/api_reader.cpython-310.pyc deleted file mode 100644 index 72db171b6329a829dc76d0451d7fe095ce036e56..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10873 zcmeHNX>24{Uaz~Ws}Hw5?KwP?P33Ts-pqKiA{)ZUIp$2lCXR_sveTPvQ`4`y-JZVY zRe2`vEiaKgO9t&m%W{Y#S;>wBC`f#O4wkA|qw=(-eVYn9|4bB~#V`6A5~eY|tySr1 zwDpcrH9BV1)TwN?t&Ux_J5JS+WviX(xK+24t!6u3)suC0JJ-oq^D^(W3!Or>AoH1a zu`^a3lX<;es+O2r9e++^S?1l;n73|JCs4|h)liL>Gz^g zc&%YAlGu zxYY?Oy2zjJwYtxR^{c(J^Dm(6?r6(B*X~^j+Rv{t9$c!^8g~AT==CYohFVo;TGe1W zGj3{ClVzC2?3;SkVh(oTirhSJ)x%f9fQ7uS@0f@327c%9i}FZfZCy*W8m7ZQ9lPdP z)C!~C{6H606t){5XuO1~+s~a|>UF}?Hgfx;`bsD4#?k4h)$9b_U?o1) z0javpQ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&y zzBL-f*CFE+V}$z&csT`7VH0fSC)E>mV-kweS4kw@_znba$D<^}%wEv0owzn3Z(W_# zk@{`C3L%6j3UR}cksndKz!u>@)zQEor$qW!z~M~YHA!PQX#i5DqLj$7Fsk#G^mm5z`R>uah)6@Pld!IIJ;k`% z*^ZHW2{5UAZu)j*N3Rv40I>wFZa@Ke+z;>H@qr`f_`S4}68C8l_fc{`B|l5a1SMal zX$lN&9J%EHvow9dY(QyyC^WKAQ#Vxun z^7pxqxDV&^vLC`GgM8~ z5V`&;eL>fx&l}}egz8T7h@5k#-s9m+Q-0!DQ*R-Qsk8_!Q+|si7jw{VggdJ~c6%Dc VSGTz?=wC{|>md%b;D$~V{|iHg1)Tr@ diff --git a/utils/__pycache__/api_reader.cpython-312.pyc b/utils/__pycache__/api_reader.cpython-312.pyc deleted file mode 100644 index 7a7265dd6878edb9c860ffa9da54ccb2ec0e74b9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18345 zcmeHvd2kzNmR~n6;s#0Z0Pp4jk`P5wl&D*xC5n_pOQH_amPna{h0q`g3J0efluQcr zxVD@MJkdtfdMctb-VC*=is{&uq5m>nwJB>nn~XL)n{*rU0NX=nw26`}Ri!F4rO9|S zTQzy_Ycv2splqi$Nu?@n>*4F~c;EfL_kQ1N{-woYq~O_^s2l(59*X+U_@X?TRN&Df z1a46*#nJ(46n|9#I;a{|1=XW!8sF6cO;9_k4eCa9@7|SQoGaEu$6^E(lnIwow}i(}BX#LRLRoq@s>dtla2VY!j$$B2K#{%I?p1|>0 zmh&9-%8it1s>Rf!N_f9T`KVEvrAAdO{RTCvW;Lwp4SG~Ft9EH6(;3e1^_}y1SRd!5 zvv?p2HT-+jKv+c5Y44{pMJabWZkBS<(0>kRQc`&*prIPx7Z~R;2lM1u=VUnO>%2PY z3HbO)4|ln}Tcvok=Yoh9?W?VHyxpXi} z4{?;ZG9XgHC4a;V6D(e(&puXl`BG9&t0ET+8i$(jvY-pY8Pikhilm>I=00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R}->c-BYiex-A1Lagk7Q{BrRM!X&&qYmNYN712sBU_lAgc5& z*GXPyqV(Fq>lL)+a~@b-C~@E+?gr#fMacM~OD)f^WMX~1m-7>7O_|q&P=L$_nOp_H zMI3;jxKfck9a$xF;M`Ifx5v++vog)KJUeT7GhV}K+Yi-cPaC>T_xoeK2)t z;MX3v!8gM9tC^)5vAPqLHX9@888Z5VTmx`%6>^Q(_9i4wB<~@?+kEaHAi0I)BP9PC z$tOq%MuO;rd{vF2koz@~-y&&7Qi7xy32Y*nR6>A11>_BC-CU$?UOMuKf}f4%L0TK8 zH!i6fwAGJ}(_6H48>6&ETeDHC(>gW^i-0uOYKu2|>1HjnafWWv?%5cmjoPM14z0Fc zt_dq~m2jWJkEET%zr8}fPnW-CH^ARHnef1l8s|`kaA;)1-{t^U3lC3F9{Jk}gvBJ& z^eq1Ej|u$aF61w#$e)jt6P_L3Fz4%-Ab;S+E!Sd3hU8GH!4RBYsUAN)3gD_B|7ndL z4#5~)cw`bmj?(lmDci3o=dY-?Ur}8m)%69{^aWM(1=aaW%5-06dR_Y)jhSx!k^=IZ O>TxX%au_M;`2Pf@m6jv` diff --git a/utils/__pycache__/api_reader.cpython-39.pyc b/utils/__pycache__/api_reader.cpython-39.pyc deleted file mode 100644 index a7c4755af356ffe4fb3d58e7dc0ad757e6076405..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17776 zcmeHveT*FEdEdJaBg;Em;mOKsx$oR@ zkNa_aXO7aX_fjX6Bc&;0r*<5-mW!j11W}5#MUl8|&_7Z)2?DeUilQjc0fGh&(w1nG z0twOPpS43`7*$dWe z=`Lnt&CfbXuHI>_b)qmSG}?{0QEN83A&Lv<8uj?OPJ6krlH@P8!j&2`vza7+t`^rW z=vpgGyn3fyuf<6*?o?GR4&z2EoVAnEbDc)}`LKSybN14U$ooTe#pj!ytF`6}8%o#e zoWk(mV5yFwG_;m%Wi2_%R?b`2Qby&JtFmv|ORnT7Fzw)a z4p&qHh^<>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&eSD(@1b~r z3aAd{95Hgdb6F00N@kfZjf5gtkI+h&h3tX6WjBnF+K6pbiIzDsn%c%5oo3qFLOef{ zl_166Q}YLE=wsEN&}iROkA?ws?b)A=g86kV#y=ETpX!p4PL?1$jg6=!TI(mz)-tx! z6Js8uYl+NN6q*9DcwME!mFmT!TWh5`neFL_xc)fcyI!x?Pvf90xi z3UrYkzU31h7|nJLUB&ya?H|g}{*O)CHr~^0=6&N&`A8(3=05SOHP83`=_&vJNNaM= diff --git a/utils/__pycache__/dash_utils.cpython-312.pyc b/utils/__pycache__/dash_utils.cpython-312.pyc deleted file mode 100644 index 9c62c8a4ca385662c14e54d5d96a493eb4248b0e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5793 zcmbVQU2GfIm7ah8h`;)$Ez7bMJ7#Rjwrp8SVkd1Z%W*bvym4%|ED~bKJ0eFOa@adV zi*hJb?RJ40S*&BAsGUMUwLputVPRKK3-vAgmZAlgS{pU@u8IiTzVuD5_0l};Id@2j zP84LZcf|XD&bdG5e&-zhHXIHLkVc>Eoto_tgg;`Vnf#5)vw2Yv?g~U8q9qi>lvt2b zl89}|k_$>oDX1y6pry2eFXiL?vgJ<&U|hC>sWx7Q3gJ|Qk11BP5KF}h@l?Dqx4qDj z>J$Z2NOcjFXv9bSB(R{Qx=9dPe$qxl(CQ&!sI`#@iINzJFKDS=(w<6?j?^yFnc7Xd zQhi3k=p)^vXF*QwA-&UQnj6_JN#Y^w1(T5=yU1?R2j3pxwHIi2gXBKaPxdaTsR1$o z^?hVN86+=2dmo=a0Nf8i??Is0&wE~kd4Bi~k>r9eHAr3ps>2IX>IHJ7Q9D3}8nuJ4 zdR*TytnWo~k{tc9m^wscW6(G-C6i;&N|I4>9LkqqbOg%7Oz2LYDS5YGu^@qZ+SN0b!DN!nUIY&6g<`4f zGVPtR3*}8^aAaiUrf+bPC#Ga1gGqxd(AL& zd6xxTqvC$sGIK@Xb>hScrW`+3sw5Q}h85EYW--W^ucQ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v)q%9Kw^M+~6&>`TJ46<$l?tj|N8wEgK z4CY$`3i>UWLq{<~AZ39GFmdnkh~MYhX+&h!(?b88{I0JI@TElYHR)y%Oc0+Akgjr5 z!@{_u#u`jQ{~pEi4M*X;8vWc+W$jrAitR${dYNc`73{kkVDIfKYZprJkAb2~e+H~S zf}ita$mWIh#HGi5Bele(<+nbKt|l(kl+rn3|EMeZpPjGP<6U?A?)2R=AH@&Vdj}Q|)_Ril-j~)A$JTm|)b|c< z#sh)ih8pV9HhYE0p3Ouk)W0Ew)c(Kz#V>T7_E1;}y&=Vt;>DymnG`8%KyrwMyjTmu zEcj0a#TP^Iv7o!*9*@MhZFIT z=|5t28?%ogV?iFZa%^O=?SHj2oSK*g|DOR(#K@pA$0>l*)Y3ywBCj{Ld2u~rZ7tf% zVgHz4*NkOs7gcDhhfX5H_C|M01jC|8+1e5F8ZFT`M!h_Q@w^EH zWUgcn1P+ee_4vYnx?q#CWxPiJ1;zmx0k9$8kVR4aTp0UYIPyq1^54RXe-t|YAng8J zIQ$2pe?76gCUmb4pIn)(edmK(!CBqq)`Xt*BO@!{tzG$EEni&iE!BiBF#COb?rSTj zKD$~orZ)uPLvca^hoAD1A&|kz*V}vR z-F-m*G!gb_`-EKs%j2t&GxKfrfrBfDR=Xx@LOaT?thRr9KDr+1Ts#D9pQ=)OF9>_K oOA&W(gy7-SUU{qbo#|(SPt1$YI>Tc8S-)S5Z+6DSetswa3!(AJ{Qv*} diff --git a/utils/__pycache__/dash_utils.cpython-36.pyc b/utils/__pycache__/dash_utils.cpython-36.pyc deleted file mode 100644 index 6ef13ef0767b88525a7cf6729f53347143edc83d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4166 zcmZu!TXPi072clP&aQ4N0Rmx+F&CS~AR!51;Sk3GSuu$tyNqL;so0y@>DKNnb6I!K zqLsXQ!j-p8RbEn+l>R{8@|xHDjDF3N|AL?Lot^~*X1b>5^zC%_xqRo$`piuIv)b(L ze-|s2|5c7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vfoubGZdLBS1qbJo5##!Euh!fH`s;7Y69>AP};lX8UD= z@C$4aEE=^zLm50`kPlQ#!I;ErtwnBO1)z--DYvQm4R!eP6QUnb^;@cbN0piMDN(=>R*F-Z8=?HH)gkW>F@xw^Un3Odi%S7Zlc9d7CBKOd>E#UH(Cbg~>d5auY zpFXz!r4yX`*?>9B92t8UXMia)9Uku*I0|OyPLnf0)-i2MR}SW&y-B}`=)ppS>@!ba zI`1o{xcGY6{{{TiSyUBk+H#l=Xs`eWK0v`T#kb@Wj5gU$lWm(?k}{gt^>mpgAwxoL zE-4;J3Oy98R98|qWbz3kDM{(1UNYHLJI@OR$U~m@%mS3WOyeHX3`_w)A`v7UPxhC^ zurGyDx;i0@&j$0vX_<>YAYWurj9}=~hLnHl`N`4__UN|qb`Ng-f|g|AGN(#XrKl=U z>AJ}~4G`$Yi=T@!Ug$=GKN6S(WiXRDDn(2?)+65~UK=lX8HMUbDhm9bnJm)u1T&Q7 zQc^jY(9R1|-}4^1Njw%N-N&*kJx42#cQnezv6PvTQj@_|haB)N_?i?RT-FvWsVSbohX)1Zg>PH85f+=;>XlQE3=Rvmo6 Ph51u;uTihh)$9KU{y|vg diff --git a/utils/__pycache__/dash_utils.cpython-39.pyc b/utils/__pycache__/dash_utils.cpython-39.pyc deleted file mode 100644 index a4fa33870b84bc0dc9cbd89f53ae5c6d6ab482f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4172 zcmZ`+&2tpT6`!83on7rpD**!e17pD0i$Px?zz)HQkrk7qgv;1*YGQjcnr`imnAutP z^rDr#oZ`w&smd`a9pK;tw_J10pV8Nxe2xz;$2R%Bp2Y}orfYg$cfbC6AHVk|YBXvV zo}1Ol&40~W*1xH7@Ts8j3%te0%(A$}S!!i0WSJe>jM{eUWNzqYUg%|h=x3F%V)~sl z2&))((porSzV)mTPMR?{oywYFGn)>l$GkJyq3|%X5-U8yJ?`@g4|sLo4QF``t$O&bK(U)%a86m;fws(z2kiDJ`;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f%`k)W^clxq%+pvqoTOdA_+Al{vnc7+WJybyip|^<`$fq^~bpd zryzcf#_oLtSOvJnAaU!Eb|-~;#<}43sYt2pX@R29UASPny)Tk2yW610tY_|i^@mqF z<@)ZhMS@eYr6%6;)OTKZ_XTOs$!NE%zF?O6{F;W7n!dZe*#ovZXHGw(~oo zcSF*?GtsuQ1d6ju&G%|s7ANU~1-)E*6z7>*alb;mY5RBfzq^0ABHGj)wn}*ovZe7} zarwf~owCRkxp*7gFY-#?>Wmb>Q~7pfv}#+ltYg`~a$eehdM&RfY=&#$TiYX+ce3Bk zj`CZhrR~dID?6pVC)aXMK@4)b=g%(;NuIi;&Nb(5T(nV89fAH0X8>NaeO$;#Dx!25 zN4$3HQlVVCJ63y8u00q%!@sEZ~q+SpKCIOBYUdTc?)TO!$1az-iwK(#C-I-H{>WV=U7?5wg4>xiJ;8hh+%^5-dMRgV}rfzSlB7^_Ehv_8}SH?{y4rI>OZ$`tJ;G(qYf~YwCyyEkB zo{wCMX18wk*S!aqr(s-00DVCb-0O|j+HiN=Rk&b@x~k&kb&(Odybapq+}ioBcx7$m zf?U})-;K*vBHQWQAXcwZSp#RH+}a--QFim0lH@ueoAXb&PBLEFmRvhJ%x;ohLFI`j z<-U zox~=f$6Y6}3GhcWZF|vN`n1t8)6Vale)n`Vdk>~Ai9+2`R~^nQmGO~sxvY)UK`vgh z@ND#Z#2VCsyOCMaeL(GryPDBRG5rK4|28}Jy85O zjQzR?Ww}VG&odT3X!IEK9yB|RdmmJkBX&r))98I5>N<4*IF(gzwbDnkJwOsD%Z&h;a%?nhkHkGOW3YyWeu_RqQUKj+&1jI;lP$)RifF^AwE P%1)YfFep*TKKK6te{7b9 diff --git a/utils/__pycache__/reader.cpython-36.pyc b/utils/__pycache__/reader.cpython-36.pyc deleted file mode 100644 index 520fdac8abfaf7406fbbae40232b28dff66d3c79..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14284 zcmeHOTWlQHd7jJe?Cgchiztec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=(gL++;6*H| zhot^PnE4FmX04Q@^cYHEz|RbZ`dKWqevZK>7`%jFc+mEyvg71J=2HnicU|uKoHn)0 zx!jx1YMt4>J@mP&QBr?H?hwgoO$SZy042nBSLfMP2s`B3Wx4+vy0D%ZE!a5Tp#X=K z=5nX2BV#-3m97#1F7gJOC|rWzA5fYgtUsh4{9V#DT3fx3?xkG%b<9!9Z+{Rq_(!3Q z{@q{-A_s;rNsy3EFg3l708-;4Oh17jb=SIU<~Cx7Wo-rp24be{GPTM;u4U}JEHIDK z?6#CxCgrx2q^j7_9gf`)moRaqN-c#R=!ACysClHgX*jI4BnHeqDwT1kZ7=(`IK2~S zY|+|?A9bR^Q*m%J06E^;p?h=S>U=*Z+jh4@$wO6>l1DJfO(X_(NSOK`utP#JIFvef zPl?Oy<4~M%f9J5JkKa9RQgD|Y5$hzal0+uBJ&5~Pr&NB?x_ydP#v5|qYR(&2k!0y{ zy*q}bI1USP-Tk7v4&yv$tRH6}+ct~Tz(u*O=aw^biR{2=mVv?!&lB$8`h%3&V0N)v z=1&Ti%x>9tva2Qkz!jfBZF3jHhfYiDFXP_vy=yWKk5hm zC;fB&lm2m}DpGsyfDTbN%-`aFdC9+J$iHxe#V-Gkj8-4b&C?WVskc_|sJgjIWF!Sw zDJ-vT@V}Op`EO+MZ(D+9!b8&Md;=nUep&vNtY*GaW{2-Fs4(ED_nQuGO_~2EqLtE+ RqK^$3gE_^B0N<@v{|o=y%g+D+ diff --git a/utils/__pycache__/reader.cpython-39.pyc b/utils/__pycache__/reader.cpython-39.pyc deleted file mode 100644 index 36123056426b8c9bbfe87503d71c87af99e10ca2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14111 zcmeHOYm6M(RjyZ8S3jnw=i%{d)?2&rY}~;+c9PYyF=n&&j$c`O*6~c@xRy;*?prg{ z<9_*8jlI*U2@7`Eje^4pLI`97<0T*r2oM1xAV7FU5g`#0|LPACNFe{<7eYu*qVSz_ zt9yE8?9H-BNJvb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