-
Notifications
You must be signed in to change notification settings - Fork 6
/
yfinance.py
62 lines (49 loc) · 1.62 KB
/
yfinance.py
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
import pandas as pd
def ingest() -> pd.DataFrame:
"""
Credit to: https://stackoverflow.com/a/76580610/1919374
"""
import pandas as pd
import requests
apiBase = "https://query2.finance.yahoo.com"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"}
def getCredentials(
cookieUrl="https://fc.yahoo.com", crumbUrl=apiBase + "/v1/test/getcrumb"
):
cookie = requests.get(cookieUrl, timeout=30).cookies
crumb = requests.get(
url=crumbUrl, cookies=cookie, headers=headers, timeout=30
).text
return {"cookie": cookie, "crumb": crumb}
def quote(symbols, credentials):
url = apiBase + "/v7/finance/quote"
params = {"symbols": ",".join(symbols), "crumb": credentials["crumb"]}
response = requests.get(
url,
params=params,
cookies=credentials["cookie"],
headers=headers,
timeout=30,
)
quotes = response.json()["quoteResponse"]["result"]
return quotes
symbols = ["GOOG", "TSLA", "AAPL", "MSFT"]
credentials = getCredentials()
quotes = quote(symbols, credentials)
if quotes:
prices = []
metric_names = []
for quote in quotes:
prices.append(quote["regularMarketPrice"])
metric_names.append(f"yf_{quote['symbol'].lower()}_price")
df = pd.DataFrame(
{
"metric_name": metric_names,
"metric_value": prices,
}
)
df["metric_timestamp"] = pd.Timestamp.utcnow()
return df
if __name__ == "__main__":
df = ingest()
print(df)