Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
131 lines (115 loc) · 6.08 KB
/
Copy pathindex.js
File metadata and controls
131 lines (115 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { dates } from './utils/dates.js'
const tickersArr = []
const generateReportBtn = document.querySelector('.generate-report-btn')
generateReportBtn.addEventListener('click', fetchStockData)
document.getElementById('ticker-input-form').addEventListener('submit', (e) => {
e.preventDefault()
const tickerInput = document.getElementById('ticker-input')
if (tickerInput.value.length > 2) {
generateReportBtn.disabled = false
const newTickerStr = tickerInput.value
tickersArr.push(newTickerStr.toUpperCase())
tickerInput.value = ''
renderTickers()
} else {
const label = document.getElementsByTagName('label')[0]
label.style.color = 'red'
label.textContent = 'You must add at least one ticker. A ticker is a 3 letter or more code for a stock. E.g TSLA for Tesla.'
}
})
function renderTickers() {
const tickersDiv = document.querySelector('.ticker-choice-display')
tickersDiv.innerHTML = ''
tickersArr.forEach((ticker) => {
const newTickerSpan = document.createElement('span')
newTickerSpan.textContent = ticker
newTickerSpan.classList.add('ticker')
tickersDiv.appendChild(newTickerSpan)
})
}
const loadingArea = document.querySelector('.loading-panel')
const apiMessage = document.getElementById('api-message')
async function fetchStockData() {
document.querySelector('.action-panel').style.display = 'none'
loadingArea.style.display = 'flex'
try {
const stockData = await Promise.all(tickersArr.map(async (ticker) => {
//const url = `https://api.polygon.io/v2/aggs/ticker/${ticker}/range/1/day/${dates.startDate}/${dates.endDate}?apiKey=ZQgz7pKxxG4Y0pe3fts2IT_fbZ5kjzUN`
const url = "https://polygon-api-worker.moondog.workers.dev/"
// Make a fetch request to the Worker
// Make a fetch request to the Worker
// send query parameters (ticker, start and end dates) on the URL
const params = new URLSearchParams({
ticker,
startDate: dates.startDate,
endDate: dates.endDate
});
console.log(`${url}?${params.toString()}`)
const response = await fetch(`${url}?${params.toString()}`, {
method: 'GET' // change to 'POST' and include a body if your worker expects POST requests
});
//const response = await fetch(url)
const data = await response.json()
const status = await response.status
if (status === 200) {
apiMessage.innerText = 'Creating report...'
delete data.request_id
return JSON.stringify(data)
} else {
loadingArea.innerText = 'There was an error fetching stock data.'
}
}))
fetchReport(stockData.join(''))
} catch (err) {
loadingArea.innerText = 'There was an error fetching stock data.'
console.error(err.message)
}
}
async function fetchReport(data) {
const messages = [
{
role: 'system',
content: 'You are a trading guru. Given data on share prices over the past 3 days, write a report of no more than 150 words describing the stocks performance and recommending whether to buy, hold or sell. Use the examples provided between ### to set the style your response.'
},
{
role: 'user',
content: `${data}
###
OK baby, hold on tight! You are going to haate this! Over the past three days, Tesla (TSLA) shares have plummetted. The stock opened at $223.98 and closed at $202.11 on the third day, with some jumping around in the meantime. This is a great time to buy, baby! But not a great time to sell! But I'm not done! Apple (AAPL) stocks have gone stratospheric! This is a seriously hot stock right now. They opened at $166.38 and closed at $182.89 on day three. So all in all, I would hold on to Tesla shares tight if you already have them - they might bounce right back up and head to the stars! They are volatile stock, so expect the unexpected. For APPL stock, how much do you need the money? Sell now and take the profits or hang on and wait for more! If it were me, I would hang on because this stock is on fire right now!!! Apple are throwing a Wall Street party and y'all invited!
###
Apple (AAPL) is the supernova in the stock sky – it shot up from $150.22 to a jaw-dropping $175.36 by the close of day three. We’re talking about a stock that’s hotter than a pepper sprout in a chilli cook-off, and it’s showing no signs of cooling down! If you’re sitting on AAPL stock, you might as well be sitting on the throne of Midas. Hold on to it, ride that rocket, and watch the fireworks, because this baby is just getting warmed up! Then there’s Meta (META), the heartthrob with a penchant for drama. It winked at us with an opening of $142.50, but by the end of the thrill ride, it was at $135.90, leaving us a little lovesick. It’s the wild horse of the stock corral, bucking and kicking, ready for a comeback. META is not for the weak-kneed So, sugar, what’s it going to be? For AAPL, my advice is to stay on that gravy train. As for META, keep your spurs on and be ready for the rally.
###
`
}
]
try {
const url = "https://open-api-worker.moondog.workers.dev/"
// Make a fetch request to the Worker
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(messages)
});
// Parse the response to a JavaScript object
const data = await response.json();
if (!response.ok) {
throw new Error(`Worker.error: ${data.error}`);
}
// Log the response to the console
console.log(data);
renderReport(data.content)
} catch (err) {
console.error(err.message)
loadingArea.innerText = 'Unable to access AI. Please refresh and try again'
}
}
function renderReport(output) {
loadingArea.style.display = 'none'
const outputArea = document.querySelector('.output-panel')
const report = document.createElement('p')
outputArea.appendChild(report)
report.textContent = output
outputArea.style.display = 'flex'
}