Spaces:
Sleeping
Sleeping
import streamlit as st | |
import requests | |
import json | |
import os | |
import numpy as np | |
import yfinance as yf | |
import datetime as dt | |
import pandas as pd | |
import pandas_ta as ta | |
from pytz import timezone | |
import plotly.graph_objects as go | |
from sklearn.linear_model import LinearRegression | |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer | |
from sklearn.model_selection import train_test_split | |
from sklearn.ensemble import RandomForestClassifier | |
from sklearn.metrics import accuracy_score | |
USERS_FILE = 'users.json' | |
API_KEYS_FILE = 'api_keys.json' | |
def load_users(): | |
if not os.path.exists(USERS_FILE): | |
with open(USERS_FILE, 'w') as file: | |
json.dump({"users": []}, file) | |
with open(USERS_FILE, 'r') as file: | |
return json.load(file) | |
def save_users(users): | |
with open(USERS_FILE, 'w') as file: | |
json.dump(users, file) | |
def login(username, password): | |
users = load_users() | |
for user in users['users']: | |
if user['username'] == username and user['password'] == password: | |
return True | |
return False | |
def signup(username, password): | |
users = load_users() | |
for user in users['users']: | |
if user['username'] == username: | |
return False | |
users['users'].append({"username": username, "password": password}) | |
save_users(users) | |
return True | |
def admin_login(username, password): | |
if username == "admin" and password == "admin": | |
return True | |
return False | |
def load_api_keys(): | |
if not os.path.exists(API_KEYS_FILE): | |
with open(API_KEYS_FILE, 'w') as file: | |
json.dump({"newsapi_key": "", "coinmarketcap_key": ""}, file) | |
with open(API_KEYS_FILE, 'r') as file: | |
return json.load(file) | |
def save_api_keys(newsapi_key, coinmarketcap_key): | |
api_keys = load_api_keys() | |
api_keys['newsapi_key'] = newsapi_key | |
api_keys['coinmarketcap_key'] = coinmarketcap_key | |
with open(API_KEYS_FILE, 'w') as file: | |
json.dump(api_keys, file) | |
def get_crypto_news(api_key, crypto_symbol, sort_by='publishedAt'): | |
url = f"https://newsapi.org/v2/everything?q={crypto_symbol}&apiKey={api_key}&language=en&sortBy={sort_by}" | |
response = requests.get(url) | |
if response.status_code == 200: | |
news_data = response.json() | |
articles = news_data.get('articles', []) | |
crypto_news = [] | |
for article in articles: | |
title = article.get('title', 'No Title') | |
description = article.get('description', 'No Description') | |
url = article.get('url', '#') | |
published_at = article.get('publishedAt', 'No Date') | |
relevancy = article.get('relevancy', 'unknown') # Ensure 'relevancy' is present | |
popularity = article.get('popularity', 'unknown') # Ensure 'popularity' is present | |
crypto_news.append({ | |
"title": title, | |
"description": description, | |
"url": url, | |
"publishedAt": published_at, | |
"relevancy": relevancy, | |
"popularity": popularity | |
}) | |
return crypto_news | |
else: | |
return [] | |
def analyze_news_sentiment(news): | |
analyzer = SentimentIntensityAnalyzer() | |
for article in news: | |
title = article['title'] | |
description = article['description'] | |
sentiment_score = analyzer.polarity_scores(title + " " + description) | |
article['sentiment'] = sentiment_score | |
return news | |
def train_price_prediction_model(data): | |
X = data[['Open', 'High', 'Low', 'Volume']] | |
y = data['Close'] | |
model = LinearRegression() | |
model.fit(X, y) | |
return model | |
def predict_crypto_price(data, model): | |
latest_data = data.iloc[-1] | |
latest_features = latest_data[['Open', 'High', 'Low', 'Volume']].values.reshape(1, -1) | |
predicted_price = model.predict(latest_features)[0] | |
return predicted_price | |
def analyze_indicators(data): | |
if 'Close' in data: | |
data['RSI'] = ta.rsi(data['Close'], length=14) | |
data['Stochastic'] = ta.stoch(data['High'], data['Low'], data['Close'], k=14, d=3)['STOCHk_14_3_3'] | |
macd = ta.macd(data['Close'], fast=12, slow=26, signal=9) | |
data['MACD'] = macd['MACD_12_26_9'] | |
data['SMA'] = ta.sma(data['Close'], length=50) | |
data['EMA'] = ta.ema(data['Close'], length=50) | |
else: | |
data['RSI'] = pd.Series([None]*len(data)) | |
data['Stochastic'] = pd.Series([None]*len(data)) | |
data['MACD'] = pd.Series([None]*len(data)) | |
data['SMA'] = pd.Series([None]*len(data)) | |
data['EMA'] = pd.Series([None]*len(data)) | |
return data | |
def calculate_indicators(data): | |
data['MA'] = data['Close'].rolling(window=10).mean() | |
data['CCI'] = (data['Close'] - data['Close'].rolling(window=20).mean()) / (0.015 * data['Close'].rolling(window=20).std()) | |
data['MACD'] = data['Close'].ewm(span=12, adjust=False).mean() - data['Close'].ewm(span=26, adjust=False).mean() | |
return data | |
def generate_signals(data): | |
buy_signal = None | |
sell_signal = None | |
# محاسبه اندیکاتورها | |
data = calculate_indicators(data) | |
data.dropna(inplace=True) | |
# آمادهسازی ویژگیها و برچسبها | |
features = data[['RSI', 'Stochastic', 'MA', 'CCI', 'MACD']] | |
labels = ((data['RSI'] < 30) & (data['Stochastic'] < 20)).astype(int) - ((data['RSI'] > 70) & (data['Stochastic'] > 80)).astype(int) | |
# تقسیم دادههای آموزش و تست | |
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42) | |
# آموزش مدل RandomForest | |
model = RandomForestClassifier(n_estimators=100, random_state=42) | |
model.fit(X_train, y_train) | |
# پیشبینی و ارزیابی مدل | |
y_pred = model.predict(X_test) | |
accuracy = accuracy_score(y_test, y_pred) | |
if 0.8 <= accuracy <= 1.0: | |
latest_data = data.iloc[-1] | |
prediction = model.predict([latest_data[['RSI', 'Stochastic', 'MA', 'CCI', 'MACD']].values]) | |
if prediction == 1: | |
buy_signal = (latest_data.name, latest_data['Close'], latest_data['Close'] * 0.95, "High Risk", 3) | |
elif prediction == -1: | |
sell_signal = (latest_data.name, latest_data['Close'], latest_data['Close'] * 1.05, "High Risk", 3) | |
return buy_signal, sell_signal | |
def get_fear_and_greed_index(): | |
response = requests.get("https://api.alternative.me/fng/?limit=1") | |
if response.status_code == 200: | |
return response.json()["data"][0]["value"] | |
else: | |
return None | |
def get_crypto_data_from_coinmarketcap(api_key, crypto_symbol): | |
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest" | |
parameters = {'symbol': crypto_symbol, 'convert': 'USD'} | |
headers = {'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': api_key} | |
response = requests.get(url, headers=headers, params=parameters) | |
data = response.json() | |
return data['data'][crypto_symbol]['quote']['USD'] | |
def display_time_information(language): | |
if language == "English": | |
st.subheader("Time Information") | |
st.write("Below are the current times for different global markets and the best trading time in Iran.") | |
else: | |
st.subheader("اطلاعات زمان") | |
st.write("در زیر زمانهای فعلی برای بازارهای جهانی و بهترین زمان معامله در ایران آورده شده است.") | |
iran_tz = timezone('Asia/Tehran') | |
utc_tz = timezone('UTC') | |
japan_tz = timezone('Asia/Tokyo') | |
europe_tz = timezone('Europe/Berlin') | |
us_tz = timezone('America/New_York') | |
iran_time = dt.datetime.now(iran_tz).strftime('%H:%M:%S') | |
utc_time = dt.datetime.now(utc_tz).strftime('%H:%M:%S') | |
japan_open = dt.datetime.now(japan_tz).replace(hour=9, minute=0, second=0, microsecond=0).strftime('%H:%M:%S') | |
europe_open = dt.datetime.now(europe_tz).replace(hour=8, minute=0, second=0, microsecond=0).strftime('%H:%M:%S') | |
us_open = dt.datetime.now(us_tz).replace(hour=9, minute=30, second=0, microsecond=0).strftime('%H:%M:%S') | |
if language == "English": | |
st.write(f"Iran Time: {iran_time}") | |
st.write(f"UTC Time: {utc_time}") | |
st.subheader("Global Crypto Markets Open Times") | |
data = { | |
"Country": ["Japan", "Europe", "USA"], | |
"Open Time": [japan_open, europe_open, us_open] | |
} | |
df = pd.DataFrame(data) | |
st.table(df) | |
st.subheader("Best Trading Time in Iran") | |
st.write("The best time for trading in Iran is when the global crypto markets are active, especially during the overlapping hours of the European and American markets.") | |
else: | |
st.write(f"زمان ایران: {iran_time}") | |
st.write(f"زمان هماهنگ جهانی: {utc_time}") | |
st.subheader("زمان باز شدن بازارهای جهانی ارز دیجیتال") | |
data = { | |
"کشور": ["ژاپن", "اروپا", "آمریکا"], | |
"زمان باز شدن": [japan_open, europe_open, us_open] | |
} | |
df = pd.DataFrame(data) | |
st.table(df) | |
st.subheader("بهترین زمان معامله در ایران") | |
st.write("بهترین زمان برای معامله در ایران زمانی است که بازارهای جهانی ارز دیجیتال فعال هستند، به ویژه در ساعت های همپوشانی بازارهای اروپا و آمریکا.") | |
def generate_learning_tips(language): | |
tips = [ | |
{"en": "Diversify your portfolio to manage risk effectively.", "fa": "سبد سرمایهگذاری خود را متنوع کنید تا ریسک را به طور مؤثری مدیریت کنید."}, | |
{"en": "Use technical analysis to identify market trends.", "fa": "از تحلیل تکنیکال برای شناسایی روندهای بازار استفاده کنید."}, | |
{"en": "Stay updated with the latest news in the crypto world.", "fa": "با آخرین اخبار دنیای ارز دیجیتال بهروز باشید."}, | |
{"en": "Understand the fundamentals of the cryptocurrencies you invest in.", "fa": "اصول اولیه ارزهای دیجیتالی که در آنها سرمایهگذاری میکنید را درک کنید."}, | |
{"en": "Use stop-loss orders to protect your investments.", "fa": "از دستورات توقف ضرر برای محافظت از سرمایهگذاریهای خود استفاده کنید."}, | |
{"en": "Regularly review your investment strategy and adjust as needed.", "fa": "استراتژی سرمایهگذاری خود را به طور منظم بازبینی کنید و در صورت نیاز آن را تنظیم کنید."}, | |
{"en": "Don't invest more than you can afford to lose.", "fa": "بیش از آنچه که میتوانید از دست بدهید سرمایهگذاری نکنید."} | |
] | |
if language == "English": | |
st.subheader("Learning Tips") | |
for tip in tips: | |
st.write(f"- {tip['en']}") | |
else: | |
st.subheader("نکات آموزشی") | |
for tip in tips: | |
st.write(f"- {tip['fa']}") | |
def main(): | |
st.title("Crypto Trading Dashboard") | |
#زبان ها | |
language = st.sidebar.selectbox("Select Language / زبان را انتخاب کنید", ("English", "فارسی")) | |
#منو کار | |
menu = ["Home", "Login", "SignUp", "Admin", "Time", "Charts", "Market Data", "News"] | |
choice = st.sidebar.selectbox("Menu", menu) | |
if choice == "Home": | |
if language == "English": | |
st.subheader("Welcome to the Crypto Trading Dashboard") | |
st.write(""" | |
This dashboard provides you with tools and insights to trade cryptocurrencies effectively. | |
You can track prices, perform technical analysis, get buy/sell signals, predict prices, and stay updated with the latest news. | |
Use the sidebar to navigate through different sections. | |
""") | |
st.write("Website: [Taha Tehrani Nasab](https://ththt.ir)") | |
st.write("© 2024 FTN. All rights reserved.") | |
else: | |
st.subheader("به داشبورد معاملات ارز دیجیتال خوش آمدید") | |
st.write(""" | |
این داشبورد ابزارها و بینشهایی را برای تجارت ارزهای دیجیتال به شما ارائه میدهد. | |
میتوانید قیمتها را پیگیری کنید، تحلیل تکنیکال انجام دهید، سیگنالهای خرید/فروش دریافت کنید، قیمتها را پیشبینی کنید و با آخرین اخبار بهروز باشید. | |
از نوار کناری برای پیمایش در بخشهای مختلف استفاده کنید. | |
""") | |
st.write("وبسایت: [Taha Tehrani nasab](https://ththt.ir)") | |
st.write("© 2024 Taha Tehrani Nasab. تمامی حقوق محفوظ است.") | |
elif choice == "Login": | |
if language == "English": | |
st.subheader("Login Section") | |
else: | |
st.subheader("بخش ورود") | |
username = st.sidebar.text_input("Username / نام کاربری") | |
password = st.sidebar.text_input("Password / رمز عبور", type='password') | |
if st.sidebar.checkbox("Login"): | |
if login(username, password): | |
st.success("Logged in as {}".format(username)) | |
if language == "English": | |
st.subheader("Select Cryptocurrency") | |
else: | |
st.subheader("انتخاب ارز دیجیتال") | |
crypto_symbol = st.selectbox("Cryptocurrency Symbol", ["BTC", "ETH", "LTC", "BCH"]) | |
end_date = dt.datetime.now() | |
start_date = end_date - dt.timedelta(days=365) | |
data = yf.download(crypto_symbol + "-USD", start=start_date, end=end_date) | |
if language == "English": | |
st.subheader(f"Price Data for {crypto_symbol}") | |
else: | |
st.subheader(f"دادههای قیمت برای {crypto_symbol}") | |
st.write(data.tail()) | |
if language == "English": | |
st.subheader(f"Technical Analysis for {crypto_symbol}") | |
else: | |
st.subheader(f"تحلیل تکنیکال برای {crypto_symbol}") | |
data = analyze_indicators(data) | |
st.write(data[['RSI', 'Stochastic', 'MACD', 'SMA', 'EMA']].tail()) | |
if language == "English": | |
st.subheader("Buy/Sell Signals") | |
else: | |
st.subheader("سیگنالهای خرید/فروش") | |
buy_signal, sell_signal = generate_signals(data) | |
if buy_signal: | |
st.success(f"Buy Signal: {buy_signal}") | |
if sell_signal: | |
st.error(f"Sell Signal: {sell_signal}") | |
if language == "English": | |
st.subheader("Price Prediction") | |
else: | |
st.subheader("پیشبینی قیمت") | |
model = train_price_prediction_model(data) | |
predicted_price = predict_crypto_price(data, model) | |
if language == "English": | |
st.write(f"The predicted price for the next trading day is: ${predicted_price:.2f}") | |
else: | |
st.write(f"قیمت پیشبینی شده برای روز معاملاتی بعدی: ${predicted_price:.2f}") | |
if language == "English": | |
st.subheader("Fear and Greed Index") | |
else: | |
st.subheader("شاخص ترس و طمع") | |
fear_and_greed_index = get_fear_and_greed_index() | |
if fear_and_greed_index: | |
st.write(f"The current Fear and Greed Index is: {fear_and_greed_index}") | |
else: | |
if language == "English": | |
st.write("Could not retrieve the Fear and Greed Index.") | |
else: | |
st.write("امکان دریافت شاخص ترس و طمع وجود ندارد.") | |
else: | |
if language == "English": | |
st.warning("Incorrect Username/Password") | |
else: | |
st.warning("نام کاربری/رمز عبور اشتباه است") | |
elif choice == "SignUp": | |
if language == "English": | |
st.subheader("Create a New Account") | |
else: | |
st.subheader("ایجاد حساب جدید") | |
new_user = st.text_input("Username / نام کاربری") | |
new_password = st.text_input("Password / رمز عبور", type='password') | |
if st.button("Sign Up"): | |
if signup(new_user, new_password): | |
if language == "English": | |
st.success("Account created successfully. You can now log in.") | |
else: | |
st.success("حساب با موفقیت ایجاد شد. اکنون میتوانید وارد شوید.") | |
else: | |
if language == "English": | |
st.warning("Username already exists. Please choose another.") | |
else: | |
st.warning("نام کاربری از قبل وجود دارد. لطفاً نام دیگری انتخاب کنید.") | |
elif choice == "Admin": | |
if language == "English": | |
st.subheader("Admin Section") | |
else: | |
st.subheader("بخش مدیریت") | |
username = st.sidebar.text_input("Admin Username / نام کاربری مدیر") | |
password = st.sidebar.text_input("Admin Password / رمز عبور مدیر", type='password') | |
if st.sidebar.checkbox("Login"): | |
if admin_login(username, password): | |
if language == "English": | |
st.success("Admin login successful") | |
st.subheader("Set API Keys") | |
else: | |
st.success("ورود مدیر موفقیتآمیز بود") | |
st.subheader("تنظیم کلیدهای API") | |
newsapi_key = st.text_input("NewsAPI Key") | |
coinmarketcap_key = st.text_input("CoinMarketCap Key") | |
if st.button("Save API Keys"): | |
save_api_keys(newsapi_key, coinmarketcap_key) | |
if language == "English": | |
st.success("API keys saved successfully") | |
else: | |
st.success("کلیدهای API با موفقیت ذخیره شد") | |
else: | |
if language == "English": | |
st.warning("Incorrect Admin Username/Password") | |
else: | |
st.warning("نام کاربری/رمز عبور مدیر اشتباه است") | |
elif choice == "Time": | |
display_time_information(language) | |
generate_learning_tips(language) | |
elif choice == "Charts": | |
if language == "English": | |
st.subheader("Cryptocurrency Charts") | |
else: | |
st.subheader("نمودارهای ارز دیجیتال") | |
crypto_symbol = st.selectbox("Cryptocurrency Symbol", ["BTC", "ETH", "LTC", "BCH", "TON","NOT"]) | |
end_date = dt.datetime.now() | |
start_date = end_date - dt.timedelta(days=365) | |
data = yf.download(crypto_symbol + "-USD", start=start_date, end=end_date) | |
if language == "English": | |
st.subheader(f"{crypto_symbol} TradingView-like Chart") | |
else: | |
st.subheader(f"نمودار شبیه TradingView برای {crypto_symbol}") | |
fig1 = go.Figure(data=[go.Candlestick(x=data.index, | |
open=data['Open'], | |
high=data['High'], | |
low=data['Low'], | |
close=data['Close'])]) | |
st.plotly_chart(fig1) | |
elif choice == "Market Data": | |
if language == "English": | |
st.subheader("Cryptocurrency Market Data") | |
else: | |
st.subheader("دادههای بازار ارز دیجیتال") | |
crypto_symbol = st.selectbox("Cryptocurrency Symbol", ["BTC", "ETH", "LTC", "BCH","TON","NOT"]) | |
api_keys = load_api_keys() | |
if 'coinmarketcap_key' in api_keys and api_keys['coinmarketcap_key']: | |
market_data = get_crypto_data_from_coinmarketcap(api_keys['coinmarketcap_key'], crypto_symbol) | |
if language == "English": | |
st.write(f"Price: ${market_data['price']:.2f}") | |
st.write(f"Market Cap: ${market_data['market_cap']:.2f}") | |
st.write(f"24h Volume: ${market_data['volume_24h']:.2f}") | |
st.write(f"Change (24h): {market_data['percent_change_24h']:.2f}%") | |
else: | |
st.write(f"قیمت: ${market_data['price']:.2f}") | |
st.write(f"ارزش بازار: ${market_data['market_cap']:.2f}") | |
st.write(f"حجم معاملات 24 ساعته: ${market_data['volume_24h']:.2f}") | |
st.write(f"تغییرات (24 ساعت): {market_data['percent_change_24h']:.2f}%") | |
else: | |
if language == "English": | |
st.warning("API key for CoinMarketCap is not set. Please contact the admin.") | |
else: | |
st.warning("کلید API برای CoinMarketCap تنظیم نشده است. لطفاً با مدیر تماس بگیرید.") | |
elif choice == "News": | |
if language == "English": | |
st.subheader("Cryptocurrency News") | |
else: | |
st.subheader("اخبار ارز دیجیتال") | |
crypto_symbol = st.selectbox("Cryptocurrency Symbol", ["BTC", "ETH", "LTC", "BCH"]) | |
api_keys = load_api_keys() | |
if 'newsapi_key' in api_keys and api_keys['newsapi_key']: | |
news = get_crypto_news(api_keys['newsapi_key'], crypto_symbol) | |
news = analyze_news_sentiment(news) | |
# Sorting and categorizing news | |
sort_by = st.radio("Sort News By", ("publishedAt", "relevancy", "popularity"), index=0) | |
news = sorted(news, key=lambda x: x[sort_by]) | |
if language == "English": | |
st.subheader(f"News for {crypto_symbol}") | |
else: | |
st.subheader(f"اخبار برای {crypto_symbol}") | |
# Paginate news | |
page = st.slider("Select page", min_value=1, max_value=(len(news) // 5) + 1) | |
news_to_display = news[(page - 1) * 5: page * 5] | |
for article in news_to_display: | |
st.write(f"Title: {article['title']}") | |
st.write(f"Description: {article['description']}") | |
st.write(f"Sentiment: {article['sentiment']}") | |
st.write(f"Published At: {article['publishedAt']}") | |
st.write(f"Read more: [Link]({article['url']})") | |
else: | |
if language == "English": | |
st.warning("API key for NewsAPI is not set. Please contact the admin.") | |
else: | |
st.warning("کلید API برای NewsAPI تنظیم نشده است. لطفاً با مدیر تماس بگیرید.") | |
if __name__ == '__main__': | |
main() |