Update app.py
#1
by
MacDash
- opened
app.py
CHANGED
|
@@ -1,267 +1,100 @@
|
|
| 1 |
import os
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
import streamlit as st
|
| 4 |
import pandas as pd
|
|
|
|
|
|
|
| 5 |
import plotly.express as px
|
|
|
|
|
|
|
|
|
|
| 6 |
import cloudscraper
|
| 7 |
-
import warnings
|
| 8 |
-
import logging
|
| 9 |
-
# Charger les variables d'environnement (si vous utilisez un .env localement)
|
| 10 |
-
load_dotenv()
|
| 11 |
-
API_KEY = os.environ.get("API_KEY")
|
| 12 |
-
headers = {
|
| 13 |
-
"Authorization": f"Bearer {API_KEY}",
|
| 14 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 15 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 16 |
-
"Chrome/115.0.0.0 Safari/537.36"
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
url = "https://archeanvision.com/api/signals/available"
|
| 20 |
-
|
| 21 |
-
# Create a cloudscraper instance
|
| 22 |
-
scraper = cloudscraper.create_scraper() # This will handle Cloudflare challenges
|
| 23 |
-
response = scraper.get(url, headers=headers)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
print(response.text)
|
| 27 |
-
|
| 28 |
-
# Load environment variables from .env
|
| 29 |
load_dotenv()
|
|
|
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
warnings.filterwarnings(
|
| 33 |
-
"ignore",
|
| 34 |
-
message="Please replace `st.experimental_get_query_params` with `st.query_params`"
|
| 35 |
-
)
|
| 36 |
-
warnings.filterwarnings(
|
| 37 |
-
"ignore",
|
| 38 |
-
message="Please replace `st.experimental_set_query_params` with `st.query_params`"
|
| 39 |
-
)
|
| 40 |
-
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
| 41 |
-
|
| 42 |
-
# Adjust Streamlit loggers to show only errors
|
| 43 |
-
logging.getLogger("streamlit.deprecation").setLevel(logging.ERROR)
|
| 44 |
-
logging.getLogger("streamlit.runtime.scriptrunner").setLevel(logging.ERROR)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# ---------------------------- #
|
| 48 |
-
# AUTO-REFRESH #
|
| 49 |
-
# ---------------------------- #
|
| 50 |
-
st.set_page_config(
|
| 51 |
-
page_title="Dashboard Auto-Refresh",
|
| 52 |
-
layout="wide"
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
REFRESH_INTERVAL = 260 # seconds
|
| 56 |
-
st.markdown(f"<meta http-equiv='refresh' content='{REFRESH_INTERVAL}'>", unsafe_allow_html=True)
|
| 57 |
-
# ---------------------------- #
|
| 58 |
-
|
| 59 |
-
LOGO_IMAGE_URL = "https://archeanvision.com/assets/archeanvision.png"
|
| 60 |
-
st.sidebar.image(LOGO_IMAGE_URL, use_container_width=True, caption="ArcheanVision")
|
| 61 |
-
|
| 62 |
-
# Get the API key from environment variables (stored in .env or Hugging Face Secrets)
|
| 63 |
if not API_KEY:
|
| 64 |
-
|
| 65 |
-
st.stop()
|
| 66 |
-
|
| 67 |
-
# --- Helper Functions Using cloudscraper ---
|
| 68 |
-
|
| 69 |
-
def get_active_markets_cloudscraper(api_key):
|
| 70 |
-
"""Retrieves the list of active markets using cloudscraper to bypass Cloudflare."""
|
| 71 |
-
headers = {
|
| 72 |
-
"Authorization": f"Bearer {api_key}",
|
| 73 |
-
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 74 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 75 |
-
"Chrome/115.0.0.0 Safari/537.36")
|
| 76 |
-
}
|
| 77 |
-
url = "https://archeanvision.com/api/signals/available"
|
| 78 |
-
scraper = cloudscraper.create_scraper()
|
| 79 |
-
response = scraper.get(url, headers=headers)
|
| 80 |
-
response.raise_for_status() # Raises an exception for HTTP errors
|
| 81 |
-
return response.json() # Assuming the endpoint returns JSON
|
| 82 |
-
|
| 83 |
-
def get_market_data_cloudscraper(api_key, market):
|
| 84 |
-
"""Retrieves market data for the given market using cloudscraper."""
|
| 85 |
-
headers = {
|
| 86 |
-
"Authorization": f"Bearer {api_key}",
|
| 87 |
-
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 88 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 89 |
-
"Chrome/115.0.0.0 Safari/537.36")
|
| 90 |
-
}
|
| 91 |
-
# Endpoint for market data (1,440 points ~ 24h); adjust as per API docs
|
| 92 |
-
url = f"https://archeanvision.com/api/signals/{market}/data"
|
| 93 |
-
scraper = cloudscraper.create_scraper()
|
| 94 |
-
response = scraper.get(url, headers=headers)
|
| 95 |
-
response.raise_for_status()
|
| 96 |
-
return response.json()
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
| 100 |
headers = {
|
| 101 |
"Authorization": f"Bearer {api_key}",
|
| 102 |
-
"User-Agent":
|
| 103 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 104 |
-
"Chrome/115.0.0.0 Safari/537.36")
|
| 105 |
}
|
| 106 |
-
url = f"https://archeanvision.com/api/signals/{market}/signals"
|
| 107 |
scraper = cloudscraper.create_scraper()
|
| 108 |
response = scraper.get(url, headers=headers)
|
| 109 |
response.raise_for_status()
|
| 110 |
return response.json()
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
Retourne le marché sélectionné à partir des paramètres d'URL ou, par défaut, le premier élément.
|
| 117 |
-
Met �� jour le paramètre de l'URL si l'utilisateur choisit un marché différent.
|
| 118 |
-
"""
|
| 119 |
-
# Récupère les paramètres sous forme de dictionnaire-like
|
| 120 |
-
params = st.query_params
|
| 121 |
-
|
| 122 |
-
# Récupérer le paramètre "market" ou définir la valeur par défaut
|
| 123 |
-
default_market = params.get("market", market_list[0])
|
| 124 |
-
# Si "market" est une liste (clé répétée), on prend le dernier (ou le premier) élément
|
| 125 |
-
if isinstance(default_market, list):
|
| 126 |
-
default_market = default_market[0]
|
| 127 |
-
|
| 128 |
-
# Trouver l'index correspondant
|
| 129 |
-
default_index = market_list.index(default_market) if default_market in market_list else 0
|
| 130 |
-
|
| 131 |
-
# Affiche un menu déroulant pour choisir le marché
|
| 132 |
-
selected = st.selectbox("Select a market:", market_list, index=default_index)
|
| 133 |
-
|
| 134 |
-
# Si l'utilisateur choisit un marché différent, on met à jour le paramètre dans l'URL
|
| 135 |
-
if selected != default_market:
|
| 136 |
-
st.query_params.market = selected # Mise à jour via la notation par attribut
|
| 137 |
-
# Vous pouvez également faire : st.query_params["market"] = selected
|
| 138 |
-
|
| 139 |
-
return selected
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
def main():
|
| 143 |
-
st.title("Active AI Crypto Markets - ArcheanVision")
|
| 144 |
-
|
| 145 |
-
st.markdown("""
|
| 146 |
-
### What is ArcheanVision?
|
| 147 |
-
**ArcheanVision** is an autonomous multi-market trading agent.
|
| 148 |
-
It operates simultaneously on multiple crypto assets, monitoring price movements
|
| 149 |
-
in real time and delivering **data** as well as **signals** (BUY, SELL, etc.)
|
| 150 |
-
to automate and optimize decision-making.
|
| 151 |
-
- **AI Agent**: Continuously analyzes crypto markets.
|
| 152 |
-
- **Multi-Market**: Manages multiple assets at once.
|
| 153 |
-
- **Live Data**: Access to streaming data feeds (SSE).
|
| 154 |
-
- **Buy/Sell Signals**: Generated in real-time to seize market opportunities.
|
| 155 |
-
Below is a dashboard showcasing the active markets, their 24h data
|
| 156 |
-
(1,440 most recent data points), and their associated signals.
|
| 157 |
-
---
|
| 158 |
-
**Join our Discord as a beta tester** to help improve the agent and the system.
|
| 159 |
-
- Official platform: [https://archeanvision.com](https://archeanvision.com)
|
| 160 |
-
- Discord link: [https://discord.gg/k9xHuM7Jr8](https://discord.gg/k9xHuM7Jr8)
|
| 161 |
-
""")
|
| 162 |
-
|
| 163 |
-
# Retrieve active markets using cloudscraper
|
| 164 |
-
try:
|
| 165 |
-
active_markets = get_active_markets_cloudscraper(API_KEY)
|
| 166 |
-
except Exception as e:
|
| 167 |
-
st.error(f"Error fetching active markets: {e}")
|
| 168 |
-
return
|
| 169 |
-
|
| 170 |
-
if not active_markets:
|
| 171 |
-
st.error("No active markets found through the API.")
|
| 172 |
-
return
|
| 173 |
-
|
| 174 |
-
# Expecting active_markets to be a list of market names, e.g. ["BTC", "ETH", ...]
|
| 175 |
-
market_list = []
|
| 176 |
-
if isinstance(active_markets, list):
|
| 177 |
-
for item in active_markets:
|
| 178 |
-
# Depending on the response structure, adjust accordingly.
|
| 179 |
-
if isinstance(item, dict) and "market" in item:
|
| 180 |
-
market_list.append(item["market"])
|
| 181 |
-
elif isinstance(item, str):
|
| 182 |
-
market_list.append(item)
|
| 183 |
-
else:
|
| 184 |
-
st.warning(f"Item missing 'market' key: {item}")
|
| 185 |
-
else:
|
| 186 |
-
st.error("The structure of 'active_markets' is not a list as expected.")
|
| 187 |
-
return
|
| 188 |
-
|
| 189 |
-
if not market_list:
|
| 190 |
-
st.error("The market list is empty or 'market' keys not found.")
|
| 191 |
-
return
|
| 192 |
-
|
| 193 |
-
selected_market = get_selected_market(market_list)
|
| 194 |
-
if not selected_market:
|
| 195 |
-
st.error("No market selected.")
|
| 196 |
-
return
|
| 197 |
-
|
| 198 |
-
st.subheader(f"Selected Market: {selected_market}")
|
| 199 |
-
st.write(f"Fetching data for **{selected_market}** ...")
|
| 200 |
-
|
| 201 |
-
# Retrieve market data using cloudscraper
|
| 202 |
-
try:
|
| 203 |
-
market_data = get_market_data_cloudscraper(API_KEY, selected_market)
|
| 204 |
-
except Exception as e:
|
| 205 |
-
st.error(f"Error fetching market data for {selected_market}: {e}")
|
| 206 |
-
return
|
| 207 |
-
|
| 208 |
-
if not market_data:
|
| 209 |
-
st.error(f"No data found for market {selected_market}.")
|
| 210 |
-
return
|
| 211 |
-
|
| 212 |
-
df = pd.DataFrame(market_data)
|
| 213 |
-
if "close_time" in df.columns:
|
| 214 |
df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', errors='coerce')
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
try:
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
except Exception as e:
|
| 247 |
-
st.error(f"Error fetching
|
| 248 |
-
return
|
| 249 |
-
|
| 250 |
-
if not signals:
|
| 251 |
-
st.warning(f"No signals found for market {selected_market}.")
|
| 252 |
-
else:
|
| 253 |
-
df_signals = pd.DataFrame(signals)
|
| 254 |
-
if 'date' in df_signals.columns:
|
| 255 |
-
df_signals['date'] = pd.to_datetime(df_signals['date'], unit='s', errors='coerce')
|
| 256 |
-
for col in df_signals.columns:
|
| 257 |
-
if df_signals[col].apply(lambda x: isinstance(x, dict)).any():
|
| 258 |
-
df_signals[col] = df_signals[col].apply(lambda x: str(x) if isinstance(x, dict) else x)
|
| 259 |
-
if 'date' in df_signals.columns:
|
| 260 |
-
df_signals = df_signals.sort_values('date', ascending=False)
|
| 261 |
-
st.write("Total number of signals:", len(df_signals))
|
| 262 |
-
st.write("Preview of the last 4 signals:")
|
| 263 |
-
st.dataframe(df_signals.head(4))
|
| 264 |
|
| 265 |
if __name__ == "__main__":
|
| 266 |
main()
|
| 267 |
-
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import streamlit as st
|
| 5 |
import plotly.express as px
|
| 6 |
+
from sklearn.linear_model import LinearRegression
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
import cloudscraper
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Load environment variables
|
|
|
|
|
|
|
|
|
|
| 12 |
load_dotenv()
|
| 13 |
+
API_KEY = os.environ.get("API_KEY")
|
| 14 |
|
| 15 |
+
# Check if API key is available
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
if not API_KEY:
|
| 17 |
+
raise ValueError("API_KEY is not set. Please add it to your environment.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# --- Helper Functions ---
|
| 20 |
+
def fetch_market_data(api_key, url):
|
| 21 |
+
"""Fetch market data using cloudscraper."""
|
| 22 |
headers = {
|
| 23 |
"Authorization": f"Bearer {api_key}",
|
| 24 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
|
|
|
|
|
|
|
| 25 |
}
|
|
|
|
| 26 |
scraper = cloudscraper.create_scraper()
|
| 27 |
response = scraper.get(url, headers=headers)
|
| 28 |
response.raise_for_status()
|
| 29 |
return response.json()
|
| 30 |
|
| 31 |
+
def preprocess_data(data):
|
| 32 |
+
"""Preprocess market data for AI analysis."""
|
| 33 |
+
df = pd.DataFrame(data)
|
| 34 |
+
if 'close_time' in df.columns:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', errors='coerce')
|
| 36 |
+
return df
|
| 37 |
+
|
| 38 |
+
def train_predictive_model(df):
|
| 39 |
+
"""Train a simple predictive model based on historical data."""
|
| 40 |
+
if 'close' not in df.columns or len(df) < 10:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
# Prepare data for training
|
| 44 |
+
scaler = StandardScaler()
|
| 45 |
+
X = np.arange(len(df)).reshape(-1, 1) # Time indices
|
| 46 |
+
y = df['close'].values.reshape(-1, 1)
|
| 47 |
+
X_scaled = scaler.fit_transform(X)
|
| 48 |
+
|
| 49 |
+
# Train linear regression model (example; replace with advanced models)
|
| 50 |
+
model = LinearRegression()
|
| 51 |
+
model.fit(X_scaled, y)
|
| 52 |
+
|
| 53 |
+
# Predict future prices
|
| 54 |
+
future_indices = np.arange(len(df), len(df) + 10).reshape(-1, 1) # Next 10 time steps
|
| 55 |
+
future_indices_scaled = scaler.transform(future_indices)
|
| 56 |
+
predictions = model.predict(future_indices_scaled)
|
| 57 |
+
|
| 58 |
+
return predictions
|
| 59 |
+
|
| 60 |
+
def display_predictions(predictions):
|
| 61 |
+
"""Display predictions in a Streamlit chart."""
|
| 62 |
+
future_dates = pd.date_range(start=pd.Timestamp.now(), periods=len(predictions), freq='H')
|
| 63 |
+
prediction_df = pd.DataFrame({'Date': future_dates, 'Predicted Close': predictions.flatten()})
|
| 64 |
+
|
| 65 |
+
fig = px.line(prediction_df, x='Date', y='Predicted Close', title="Predicted Price Movement")
|
| 66 |
+
st.plotly_chart(fig)
|
| 67 |
+
|
| 68 |
+
# --- Main Application ---
|
| 69 |
+
def main():
|
| 70 |
+
st.title("AI-Driven Stock & Crypto Dashboard")
|
| 71 |
+
|
| 72 |
+
# Fetch active markets from API
|
| 73 |
+
url_active_markets = "https://archeanvision.com/api/signals/available"
|
| 74 |
try:
|
| 75 |
+
active_markets = fetch_market_data(API_KEY, url_active_markets)
|
| 76 |
+
market_list = [market['market'] for market in active_markets]
|
| 77 |
+
selected_market = st.selectbox("Select a Market", market_list)
|
| 78 |
+
|
| 79 |
+
# Fetch market data for the selected market
|
| 80 |
+
url_market_data = f"https://archeanvision.com/api/signals/{selected_market}/data"
|
| 81 |
+
market_data = fetch_market_data(API_KEY, url_market_data)
|
| 82 |
+
|
| 83 |
+
# Preprocess and display raw data
|
| 84 |
+
df = preprocess_data(market_data)
|
| 85 |
+
st.write("Market Data Overview:")
|
| 86 |
+
st.dataframe(df.head())
|
| 87 |
+
|
| 88 |
+
# Train predictive model and display predictions
|
| 89 |
+
predictions = train_predictive_model(df)
|
| 90 |
+
if predictions is not None:
|
| 91 |
+
st.write(f"Predicted price movement for {selected_market}:")
|
| 92 |
+
display_predictions(predictions)
|
| 93 |
+
else:
|
| 94 |
+
st.warning("Insufficient data or missing 'close' column for prediction.")
|
| 95 |
+
|
| 96 |
except Exception as e:
|
| 97 |
+
st.error(f"Error fetching or processing data: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
if __name__ == "__main__":
|
| 100 |
main()
|
|
|