Dmtlant commited on
Commit
b6a7bc8
·
verified ·
1 Parent(s): aee26b3

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +34 -86
index.html CHANGED
@@ -9,49 +9,36 @@
9
  <script src="https://cdn.tailwindcss.com"></script>
10
  </head>
11
  <body class="bg-gray-100 text-gray-800 font-sans">
12
-
13
  <div class="container mx-auto p-4">
14
- <!-- Заголовок -->
15
  <h1 class="text-3xl font-bold text-center mb-6">Crypto Trading Advisor</h1>
16
 
17
- <!-- Секция выбора криптовалюты -->
18
- <div class="flex justify-center mb-4 flex-wrap">
19
- <select id="crypto-select" class="p-2 border border-gray-300 rounded-md shadow-md w-full sm:w-auto">
20
  <option value="">Загрузка криптовалют...</option>
21
  </select>
22
- <button id="get-advice" class="ml-4 px-4 py-2 bg-blue-500 text-white rounded-md shadow-md hover:bg-blue-600 w-full sm:w-auto">
23
  Получить совет
24
  </button>
25
  </div>
26
 
27
  <!-- Результаты -->
28
  <div id="result" class="bg-white p-6 rounded-md shadow-md">
29
- <p class="text-center text-gray-500">Выберите криптовалюту, чтобы увидеть советы, графики и новости.</p>
30
  </div>
31
 
32
  <!-- График -->
33
  <div class="mt-6">
34
  <canvas id="crypto-chart" class="bg-white p-4 rounded-md shadow-md"></canvas>
35
  </div>
36
-
37
- <!-- Новости -->
38
- <div id="news-section" class="mt-6 bg-white p-6 rounded-md shadow-md">
39
- <h2 class="text-xl font-bold mb-4">Новости</h2>
40
- <ul id="news-list" class="list-disc pl-5">
41
- <li class="text-gray-500">Здесь появятся новости о криптовалютах.</li>
42
- </ul>
43
- </div>
44
  </div>
45
 
46
  <script>
47
  const API_BASE = 'https://api.coingecko.com/api/v3';
48
- const NEWS_API_KEY = 'cd3cc4c35c654b6f95db05a5a3bc5004'; // Замените на ваш ключ API с https://newsapi.org/
49
- const NEWS_API_URL = 'https://newsapi.org/v2/everything';
50
  const resultDiv = document.getElementById('result');
51
  const select = document.getElementById('crypto-select');
52
  const button = document.getElementById('get-advice');
53
  const chartCanvas = document.getElementById('crypto-chart');
54
- const newsList = document.getElementById('news-list');
55
  let chartInstance;
56
 
57
  // Загрузка списка криптовалют
@@ -81,23 +68,10 @@
81
  }
82
  }
83
 
84
- // Загрузка новостей
85
- async function fetchNews(query) {
86
- try {
87
- const response = await fetch(`${NEWS_API_URL}?q=${query}&apiKey=${NEWS_API_KEY}`);
88
- const data = await response.json();
89
- return data.articles;
90
- } catch (error) {
91
- console.error('Ошибка при загрузке новостей:', error);
92
- newsList.innerHTML = `<li class="text-red-500">Ошибка при загрузке новостей.</li>`;
93
- }
94
- }
95
-
96
  // Построение графика цен
97
- function renderChart(prices, volumes, predictions = []) {
98
  const labels = prices.map((_, index) => `Day ${index + 1}`);
99
- const priceData = prices.map(price => price[1]);
100
- const volumeData = volumes.map(volume => volume[1]);
101
 
102
  if (chartInstance) {
103
  chartInstance.destroy(); // Уничтожаем старый график, если он существует
@@ -110,75 +84,51 @@
110
  datasets: [
111
  {
112
  label: 'Цена (USD)',
113
- data: priceData,
114
  backgroundColor: 'rgba(59, 130, 246, 0.2)',
115
  borderColor: 'rgba(59, 130, 246, 1)',
116
  borderWidth: 2,
117
  fill: true,
118
  },
119
- {
120
- label: 'Объем торгов (USD)',
121
- data: volumeData,
122
- backgroundColor: 'rgba(34, 197, 94, 0.2)',
123
- borderColor: 'rgba(34, 197, 94, 1)',
124
- borderWidth: 2,
125
- fill: true,
126
- },
127
- {
128
- label: 'Прогноз цены',
129
- data: predictions,
130
- borderColor: 'rgba(255, 99, 132, 1)',
131
- borderWidth: 2,
132
- borderDash: [5, 5],
133
- fill: false,
134
- },
135
  ],
136
  },
137
  options: {
138
  responsive: true,
139
  plugins: {
140
  legend: {
141
- display: true,
142
  },
143
  },
144
  },
145
  });
146
  }
147
 
148
- // Анализ с помощью LSTM
149
- async function analyzeWithLSTM(prices, callback) {
 
150
  const data = prices.map(price => price[1]);
151
- const normalizedData = data.map(value => value / Math.max(...data)); // Нормализация данных
152
-
153
- const inputs = tf.tensor(normalizedData.slice(0, -1));
154
- const targets = tf.tensor(normalizedData.slice(1));
155
 
 
156
  const model = tf.sequential();
157
- model.add(tf.layers.lstm({ units: 50, inputShape: [1, 1], returnSequences: false }));
158
  model.add(tf.layers.dense({ units: 1 }));
159
 
160
  model.compile({ optimizer: 'adam', loss: 'meanSquaredError' });
161
 
162
- const inputReshaped = inputs.reshape([inputs.size, 1, 1]);
163
- const targetReshaped = targets.reshape([targets.size, 1]);
164
-
165
- const predictions = [];
166
-
167
- // Визуализация обучения
168
- await model.fit(inputReshaped, targetReshaped, {
169
  epochs: 50,
170
- callbacks: {
171
- onEpochEnd: (epoch, logs) => {
172
- const prediction = model.predict(inputReshaped);
173
- const predData = prediction.dataSync();
174
- predictions.length = 0; // Очищаем массив
175
- predictions.push(...predData.map(v => v * Math.max(...data)));
176
- callback(predictions);
177
- },
178
- },
179
  });
180
 
181
- return predictions;
 
 
 
 
 
 
182
  }
183
 
184
  // Обработчик кнопки
@@ -193,19 +143,17 @@
193
  const data = await fetchCryptoData(crypto);
194
 
195
  if (data) {
196
- const { prices, total_volumes } = data;
197
-
198
- const predictions = await analyzeWithLSTM(prices, (updatedPredictions) => {
199
- renderChart(prices, total_volumes, updatedPredictions);
200
- });
201
 
202
- renderChart(prices, total_volumes, predictions);
 
203
 
204
- const news = await fetchNews(crypto);
205
- newsList.innerHTML = news
206
- .slice(0, 5)
207
- .map(article => `<li><a href="${article.url}" target="_blank" class="text-blue-500">${article.title}</a></li>`)
208
- .join('');
209
  }
210
  });
211
 
 
9
  <script src="https://cdn.tailwindcss.com"></script>
10
  </head>
11
  <body class="bg-gray-100 text-gray-800 font-sans">
 
12
  <div class="container mx-auto p-4">
 
13
  <h1 class="text-3xl font-bold text-center mb-6">Crypto Trading Advisor</h1>
14
 
15
+ <!-- Выбор криптовалюты -->
16
+ <div class="flex justify-center mb-4">
17
+ <select id="crypto-select" class="p-2 border border-gray-300 rounded-md shadow-md">
18
  <option value="">Загрузка криптовалют...</option>
19
  </select>
20
+ <button id="get-advice" class="ml-4 px-4 py-2 bg-blue-500 text-white rounded-md shadow-md hover:bg-blue-600">
21
  Получить совет
22
  </button>
23
  </div>
24
 
25
  <!-- Результаты -->
26
  <div id="result" class="bg-white p-6 rounded-md shadow-md">
27
+ <p class="text-center text-gray-500">Выберите криптовалюту, чтобы увидеть советы и графики.</p>
28
  </div>
29
 
30
  <!-- График -->
31
  <div class="mt-6">
32
  <canvas id="crypto-chart" class="bg-white p-4 rounded-md shadow-md"></canvas>
33
  </div>
 
 
 
 
 
 
 
 
34
  </div>
35
 
36
  <script>
37
  const API_BASE = 'https://api.coingecko.com/api/v3';
 
 
38
  const resultDiv = document.getElementById('result');
39
  const select = document.getElementById('crypto-select');
40
  const button = document.getElementById('get-advice');
41
  const chartCanvas = document.getElementById('crypto-chart');
 
42
  let chartInstance;
43
 
44
  // Загрузка списка криптовалют
 
68
  }
69
  }
70
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  // Построение графика цен
72
+ function renderChart(prices) {
73
  const labels = prices.map((_, index) => `Day ${index + 1}`);
74
+ const data = prices.map(price => price[1]);
 
75
 
76
  if (chartInstance) {
77
  chartInstance.destroy(); // Уничтожаем старый график, если он существует
 
84
  datasets: [
85
  {
86
  label: 'Цена (USD)',
87
+ data: data,
88
  backgroundColor: 'rgba(59, 130, 246, 0.2)',
89
  borderColor: 'rgba(59, 130, 246, 1)',
90
  borderWidth: 2,
91
  fill: true,
92
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  ],
94
  },
95
  options: {
96
  responsive: true,
97
  plugins: {
98
  legend: {
99
+ display: false,
100
  },
101
  },
102
  },
103
  });
104
  }
105
 
106
+ // Анализ с помощью TensorFlow.js
107
+ async function analyzeWithNeuralNetwork(prices) {
108
+ // Подготовка данных для нейросети
109
  const data = prices.map(price => price[1]);
110
+ const inputs = tf.tensor(data.slice(0, -1)); // Все кроме последнего дня
111
+ const targets = tf.tensor(data.slice(1)); // Все кроме первого дня (на один шаг вперёд)
 
 
112
 
113
+ // Создание простой модели
114
  const model = tf.sequential();
115
+ model.add(tf.layers.dense({ units: 10, activation: 'relu', inputShape: [1] }));
116
  model.add(tf.layers.dense({ units: 1 }));
117
 
118
  model.compile({ optimizer: 'adam', loss: 'meanSquaredError' });
119
 
120
+ // Тренировка модели
121
+ await model.fit(inputs.reshape([inputs.size, 1]), targets.reshape([targets.size, 1]), {
 
 
 
 
 
122
  epochs: 50,
 
 
 
 
 
 
 
 
 
123
  });
124
 
125
+ // Прогноз
126
+ const prediction = model.predict(tf.tensor([data[data.length - 1]]).reshape([1, 1]));
127
+ const predictedValue = prediction.dataSync()[0];
128
+
129
+ return predictedValue > data[data.length - 1]
130
+ ? 'Цена, вероятно, вырастет. Рекомендуется держать или покупать.'
131
+ : 'Цена, вероятно, снизится. Рекомендуется продавать.';
132
  }
133
 
134
  // Обработчик кнопки
 
143
  const data = await fetchCryptoData(crypto);
144
 
145
  if (data) {
146
+ // График
147
+ renderChart(data.prices);
 
 
 
148
 
149
+ // Анализ
150
+ const advice = await analyzeWithNeuralNetwork(data.prices);
151
 
152
+ // Результаты
153
+ resultDiv.innerHTML = `
154
+ <h2 class="text-xl font-bold">${crypto.toUpperCase()}</h2>
155
+ <p>${advice}</p>
156
+ `;
157
  }
158
  });
159