QAway-to commited on
Commit
c02f97a
·
1 Parent(s): 062dd93

New tabs and functions v1.8

Browse files
Files changed (2) hide show
  1. core/crypto_dashboard.py +27 -24
  2. requirements.txt +3 -1
core/crypto_dashboard.py CHANGED
@@ -1,24 +1,22 @@
1
  """
2
  🇬🇧 Module: crypto_dashboard.py
3
- Purpose: Unified dashboard for live & historical crypto analytics (Binance + TradingView)
4
  🇷🇺 Модуль: crypto_dashboard.py
5
- Назначение: Единый дашборд для рыночного и исторического анализа крипты.
6
  """
7
 
8
  import requests
9
  import pandas as pd
 
10
  import plotly.express as px
11
  import plotly.graph_objects as go
12
- from datetime import datetime, timedelta
13
- from tvDatafeed import TvDatafeed, Interval
14
  from services.llm_client import llm_service
15
 
16
  BINANCE_API = "https://api.binance.com/api/v3"
17
- tv = TvDatafeed() # без авторизации — работает для публичных тикеров
18
 
19
 
20
  # === Binance data (live candles) ===
21
- def get_binance_klines(symbol: str = "BTCUSDT", interval="1d", limit=365):
22
  url = f"{BINANCE_API}/klines?symbol={symbol}&interval={interval}&limit={limit}"
23
  data = requests.get(url).json()
24
  df = pd.DataFrame(data, columns=[
@@ -30,20 +28,22 @@ def get_binance_klines(symbol: str = "BTCUSDT", interval="1d", limit=365):
30
  return df
31
 
32
 
33
- # === TradingView data (extended history) ===
34
- def get_tv_history(symbols: list[str], exchange="BINANCE", bars=1000):
35
  frames = []
36
  for s in symbols:
37
  try:
38
- df = tv.get_hist(symbol=s.replace("USDT", ""), exchange=exchange, interval=Interval.in_daily, n_bars=bars)
 
 
 
39
  df["symbol"] = s
40
  frames.append(df)
41
  except Exception:
42
  continue
43
  if not frames:
44
  return pd.DataFrame()
45
- df_all = pd.concat(frames).reset_index()
46
- return df_all
47
 
48
 
49
  # === Build Dashboard ===
@@ -51,29 +51,34 @@ def build_crypto_dashboard(selected_assets: list[str], start_date: str, end_date
51
  if not selected_assets:
52
  selected_assets = ["BTCUSDT", "ETHUSDT", "BNBUSDT"]
53
 
54
- # --- Binance multi-asset (recent) ---
55
  recent_frames = []
56
  for sym in selected_assets:
57
  df = get_binance_klines(sym, "1d", 180)
58
  recent_frames.append(df.assign(symbol=sym))
59
  df_recent = pd.concat(recent_frames)
 
60
  fig_recent = px.line(
61
  df_recent, x="timestamp", y="close", color="symbol",
62
- title="Market Prices (Binance, recent 6 months)", template="plotly_dark"
 
63
  )
64
  fig_recent.update_layout(height=420, legend_title_text="Asset")
65
 
66
- # --- TradingView history (normalized) ---
67
- df_hist = get_tv_history(selected_assets)
68
  if not df_hist.empty:
69
  df_hist["returns"] = df_hist.groupby("symbol")["close"].apply(lambda x: x / x.iloc[0] - 1)
70
  fig_hist = px.line(df_hist, x="datetime", y="returns", color="symbol",
71
- title="Historical Normalized Performance (TradingView)",
72
  template="plotly_dark")
73
  fig_hist.update_layout(height=420)
74
  else:
75
  fig_hist = go.Figure()
76
- fig_hist.add_annotation(text="No TradingView data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
 
 
 
77
 
78
  # --- AI Market Summary ---
79
  summary = _generate_ai_summary(df_recent, df_hist, selected_assets)
@@ -94,14 +99,12 @@ def _generate_ai_summary(df_recent, df_hist, assets):
94
  growth_text = ", ".join(growth)
95
 
96
  prompt = f"""
97
- Analyze current crypto market based on these assets:
98
- {', '.join(assets)}.
99
-
100
- Performance last months: {growth_text}.
101
- Generate a concise summary:
102
  - Market direction (bullish/bearish)
103
- - Relative leaders/laggards
104
- - Risk tone and volatility
105
  - Short-term outlook
106
  """
107
  summary = ""
 
1
  """
2
  🇬🇧 Module: crypto_dashboard.py
3
+ Purpose: Unified dashboard for live & historical crypto analytics (Binance + Yahoo Finance)
4
  🇷🇺 Модуль: crypto_dashboard.py
5
+ Назначение: Единый дашборд для анализа крипторынка на Binance и Yahoo.
6
  """
7
 
8
  import requests
9
  import pandas as pd
10
+ import yfinance as yf
11
  import plotly.express as px
12
  import plotly.graph_objects as go
 
 
13
  from services.llm_client import llm_service
14
 
15
  BINANCE_API = "https://api.binance.com/api/v3"
 
16
 
17
 
18
  # === Binance data (live candles) ===
19
+ def get_binance_klines(symbol: str = "BTCUSDT", interval="1d", limit=180):
20
  url = f"{BINANCE_API}/klines?symbol={symbol}&interval={interval}&limit={limit}"
21
  data = requests.get(url).json()
22
  df = pd.DataFrame(data, columns=[
 
28
  return df
29
 
30
 
31
+ # === Yahoo Finance historical data ===
32
+ def get_yf_history(symbols: list[str]):
33
  frames = []
34
  for s in symbols:
35
  try:
36
+ ticker = s.replace("USDT", "-USD")
37
+ df = yf.download(ticker, period="5y", interval="1d", progress=False)
38
+ df = df.reset_index()[["Date", "Close"]]
39
+ df.columns = ["datetime", "close"]
40
  df["symbol"] = s
41
  frames.append(df)
42
  except Exception:
43
  continue
44
  if not frames:
45
  return pd.DataFrame()
46
+ return pd.concat(frames, ignore_index=True)
 
47
 
48
 
49
  # === Build Dashboard ===
 
51
  if not selected_assets:
52
  selected_assets = ["BTCUSDT", "ETHUSDT", "BNBUSDT"]
53
 
54
+ # --- Binance recent ---
55
  recent_frames = []
56
  for sym in selected_assets:
57
  df = get_binance_klines(sym, "1d", 180)
58
  recent_frames.append(df.assign(symbol=sym))
59
  df_recent = pd.concat(recent_frames)
60
+
61
  fig_recent = px.line(
62
  df_recent, x="timestamp", y="close", color="symbol",
63
+ title="Market Prices (Binance, recent 6 months)",
64
+ template="plotly_dark"
65
  )
66
  fig_recent.update_layout(height=420, legend_title_text="Asset")
67
 
68
+ # --- Yahoo historical normalized ---
69
+ df_hist = get_yf_history(selected_assets)
70
  if not df_hist.empty:
71
  df_hist["returns"] = df_hist.groupby("symbol")["close"].apply(lambda x: x / x.iloc[0] - 1)
72
  fig_hist = px.line(df_hist, x="datetime", y="returns", color="symbol",
73
+ title="Historical Normalized Performance (Yahoo Finance)",
74
  template="plotly_dark")
75
  fig_hist.update_layout(height=420)
76
  else:
77
  fig_hist = go.Figure()
78
+ fig_hist.add_annotation(
79
+ text="No Yahoo Finance data available",
80
+ xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False
81
+ )
82
 
83
  # --- AI Market Summary ---
84
  summary = _generate_ai_summary(df_recent, df_hist, selected_assets)
 
99
  growth_text = ", ".join(growth)
100
 
101
  prompt = f"""
102
+ Analyze the crypto market based on these assets: {', '.join(assets)}.
103
+ Performance (last 6 months): {growth_text}.
104
+ Give a concise professional summary:
 
 
105
  - Market direction (bullish/bearish)
106
+ - Volatility trends
107
+ - Leaders vs laggards
108
  - Short-term outlook
109
  """
110
  summary = ""
requirements.txt CHANGED
@@ -5,4 +5,6 @@ httpx
5
  pandas
6
  matplotlib
7
  plotly
8
- tvDatafeed>=1.0.9
 
 
 
5
  pandas
6
  matplotlib
7
  plotly
8
+ yfinance>=0.2.43
9
+ plotly>=6.3.1
10
+