Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions Predict-Ethereum/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.env
myenv/

Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 16 additions & 0 deletions Predict-Ethereum/EthereumPricePrediction/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for EthereumPricePrediction project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EthereumPricePrediction.settings')

application = get_asgi_application()
83 changes: 83 additions & 0 deletions Predict-Ethereum/EthereumPricePrediction/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""
Django settings for EthereumPricePrediction project.

Generated by 'django-admin startproject' using Django 5.0.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

import os
from pathlib import Path
from decouple import config

SECRET_KEY = config('SECRET_KEY')

BASE_DIR = Path(__file__).resolve().parent.parent

DEBUG = True

ALLOWED_HOSTS = []



# Application definition
INSTALLED_APPS = [
'mainapp.app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap5',
]


MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Keep this for static files
]

ROOT_URLCONF = 'EthereumPricePrediction.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'EthereumPricePrediction.wsgi.application'



# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Media files
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
25 changes: 25 additions & 0 deletions Predict-Ethereum/EthereumPricePrediction/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
URL configuration for EthereumPricePrediction project.

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mainapp.urls',namespace='mainapp')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
16 changes: 16 additions & 0 deletions Predict-Ethereum/EthereumPricePrediction/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for EthereumPricePrediction project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EthereumPricePrediction.settings')

application = get_wsgi_application()
15 changes: 15 additions & 0 deletions Predict-Ethereum/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Ethereum Price Prediction

## Project Overview
This project predicts Ethereum prices using machine learning models, specifically Random Forest and Extra Trees. The model leverages data sourced from an API(coingecko.com) over a 365-day period.

## Features
- Predicts Ethereum price based on historical data.
- Uses machine learning algorithms for accurate predictions.

## Requirements
- Python 3.9
- Django
- Pandas
- NumPy
- Scikit-learn
4 changes: 4 additions & 0 deletions Predict-Ethereum/images/Analytics.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/Background.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions Predict-Ethereum/images/Concept.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions Predict-Ethereum/images/Hamburger.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/Human Working.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions Predict-Ethereum/images/Response.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions Predict-Ethereum/images/analytics_black_24dp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions Predict-Ethereum/images/back_hand_black_24dp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/facebook.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions Predict-Ethereum/images/insights_black_24dp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/instagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/twitter.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Predict-Ethereum/images/youtube.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
3 changes: 3 additions & 0 deletions Predict-Ethereum/mainapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions Predict-Ethereum/mainapp/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class MainappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mainapp'
Empty file.
Binary file not shown.
Binary file not shown.
3 changes: 3 additions & 0 deletions Predict-Ethereum/mainapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
139 changes: 139 additions & 0 deletions Predict-Ethereum/mainapp/prediction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@

import pandas as pd
import requests
from datetime import datetime, timedelta
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
import os.path
import pickle

# Function to fetch historical Ethereum price data from CoinGecko API
def fetch_ethereum_data():
# Make a request to the CoinGecko API to fetch historical Ethereum price data
response = requests.get('https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=usd&days=365')

# Check if the request was successful
if response.status_code == 200:
# Parse the response JSON data
ethereum_data = response.json()

# Extract relevant data from the response
prices = ethereum_data['prices']
ethereum_df = pd.DataFrame(prices, columns=['Timestamp', 'Price'])

# Convert timestamp to datetime
ethereum_df['Timestamp'] = pd.to_datetime(ethereum_df['Timestamp'], unit='ms')

return ethereum_df
else:
# If the request failed, return None
print("Error in API")
return None

# Function to train the model
def train_model(X, y):
# Feature scaling using StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # Scale the features

# Hyperparameter tuning for Random Forest
rf_param_grid = {'n_estimators': [100, 200, 300],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10]}
rf_grid_search = GridSearchCV(RandomForestRegressor(), rf_param_grid, cv=5)
rf_grid_search.fit(X_scaled, y)
best_rf_model = rf_grid_search.best_estimator_

# Hyperparameter tuning for Extra Trees
et_param_grid = {'n_estimators': [100, 200, 300],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10]}
et_grid_search = GridSearchCV(ExtraTreesRegressor(), et_param_grid, cv=5)
et_grid_search.fit(X_scaled, y)
best_et_model = et_grid_search.best_estimator_

return best_rf_model, best_et_model, scaler # Return scaler for future scaling

# Function to check if the model needs to be retrained
def check_if_retrain_needed(ethereum_data):
# Check if the model file exists
if not os.path.exists("trained_model.pkl"):
return True

# Check the last modification time of the model file
last_modified_time = datetime.fromtimestamp(os.path.getmtime("trained_model.pkl"))

# Check if the last training time is more than a day ago
if datetime.now() - last_modified_time > timedelta(days=1):
return True
else:
return False

# Load historical Ethereum price data from the CoinGecko API
ethereum_data = fetch_ethereum_data()

if ethereum_data is not None and check_if_retrain_needed(ethereum_data):

ethereum_data['Year'] = ethereum_data['Timestamp'].dt.year
ethereum_data['Month'] = ethereum_data['Timestamp'].dt.month
ethereum_data['Day'] = ethereum_data['Timestamp'].dt.day
ethereum_data['Weekday'] = ethereum_data['Timestamp'].dt.weekday

# Split data into features (X) and target variable (y)
X = ethereum_data[['Year', 'Month', 'Day', 'Weekday']]
y = ethereum_data['Price']

# Train the model
best_rf_model, best_et_model, scaler = train_model(X, y)

# Save the trained model and scaler
with open("trained_model.pkl", "wb") as f:
pickle.dump((best_rf_model, best_et_model, scaler), f)

elif ethereum_data is not None and not check_if_retrain_needed(ethereum_data):
print("Model is already up to date, no need to retrain.")

else:
print("Failed to fetch Ethereum data from the CoinGecko API.")

# Load the pre-trained model and scaler
if os.path.exists("trained_model.pkl"):
with open("trained_model.pkl", "rb") as f:
best_rf_model, best_et_model, scaler = pickle.load(f)

# Random Forest
def predict_prices_for_future_random_forest(date):
# Preprocess input date provided by the user
date = pd.to_datetime(date)
year = date.year
month = date.month
day = date.day
weekday = date.weekday()

# Feature scaling for prediction using the stored scaler
scaled_features_for_date = scaler.transform([[year, month, day, weekday]])

# Make prediction using the best Random Forest model
predicted_price = best_rf_model.predict(scaled_features_for_date)[0]

# Return tuple of predicted price and default value for predicted high and low
return predicted_price, predicted_price + 100, predicted_price - 200

#Extra Trees

def predict_prices_for_future_extra_trees(date):

date = pd.to_datetime(date)
year = date.year
month = date.month
day = date.day
weekday = date.weekday()


scaled_features_for_date = scaler.transform([[year, month, day, weekday]])


predicted_price = best_et_model.predict(scaled_features_for_date)[0]

return predicted_price, predicted_price + 100, predicted_price - 200
Loading
Loading