-
Notifications
You must be signed in to change notification settings - Fork 0
/
yfinance_api.py
189 lines (155 loc) · 6.15 KB
/
yfinance_api.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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 15:50:42 2024
@author: evan_
"""
from typing import Tuple
from datetime import datetime, timedelta
import pandas as pd
import yfinance as yf # type: ignore
import streamlit as st
from pprint import pprint
# ---------------------------------------------------------------------------- #
def get_investment_names(tickers: list[str]) -> Tuple[str, pd.DataFrame]:
"""
Retrieve investment names for list of tickers.
If invalid ticker is in list, err contains an error message with the invalid ticker and the returned df is empty.
Args:
tickers (list[str]): list of tickers
Returns:
str:
If an invalid ticker is included in list, message specify
invalid ticker. Empty string if no errors.
pd.DataFrame:
Column Heading(s): shortName,
Index: ticker
df Contents: Short Name for each investment. Empty df if errors.
"""
err = ""
investment_names = pd.DataFrame()
for t in tickers:
try:
investment_names.loc[t, "longName"] = yf.Ticker(t).info["longName"]
except:
err = f"Invalid Ticker: {t}"
investment_names = pd.DataFrame() # return empty df if error
return err, investment_names # return immediately if error
return err, investment_names
def get_max_inception_date(tickers: list[str]) -> datetime:
"""Returns max inception date from a list of investments
Args:
tickers (list[str]): list of investment tickers
Returns:
datetime: maximum inception date in Epoch UTC
"""
max_inception_date: datetime = 0
for t in tickers:
d = yf.Ticker(t).info["firstTradeDateEpochUtc"]
if d > max_inception_date:
max_inception_date = d
return max_inception_date
def get_names_and_inceptions(tickers: list[str]) -> Tuple[str, pd.DataFrame]:
"""
Retrieve investment names and inception dates for list of tickers.
If invalid ticker is in list, err contains an error message with the invalid ticker and the returned df is empty.
Args:
tickers (list[str]): list of tickers
Returns:
str:
If an invalid ticker is included in list, message specify
invalid ticker. Empty string if no errors.
pd.DataFrame:
Column Heading(s): Name, Inception
Index: ticker
df Contents:
Long Name for each investment. Inception Date for each investment as datetime object.
Empty df if errors.
"""
err = ""
names_inception = pd.DataFrame()
for t in tickers:
try:
info = yf.Ticker(t).info
names_inception.loc[t, "Name"] = info["longName"]
d = info["firstTradeDateEpochUtc"]
names_inception.loc[t, "Inception"] = d
except:
err = f"Invalid Ticker: {t}"
investment_names = pd.DataFrame() # return empty df if error
return err, investment_names # return immediately if error
if err == "":
names_inception["Inception"] = pd.to_datetime(
names_inception['Inception'], unit='s', utc=True)
return err, names_inception
# ---------------------------------------------------------------------------- #
def get_adj_daily_close(
tickers: list[str], start_date: str | datetime, end_date: str | datetime
) -> pd.DataFrame:
"""
Retrieve adjusted daily closing prices for a list of tickers over a specified
date range. Order of columns in returned df is same as order in tickers argument.
Note: Assumes that the tickers are valid. So, recommendation is call the get_investment_names
function first. That function includes an error if any entry in tickers is invalid.
Args:
tickers (list[str]): List of tickers to be retrieved
start_date (str): Start date in format YYYY-MM-DD
end_date (str): End date in format YYYY-MM-DD
Returns:
pd.DataFrame:
Column Heading(s): tickers
Index: Date
df Contents: Adjusted daily closing prices
"""
# Retrieve daily
adj_close = yf.download(tickers, start=start_date, end=end_date, interval="1d")[
"Adj Close"
][tickers]
return adj_close
def get_previous_close(ticker:str)-> float:
"""_summary_
Args:
ticker (str): Ticker of investment
Returns:
float: previous day closing price
"""
return yf.Ticker(ticker).info['previousClose']
# ---------------------------------------------------------------------------- #
if __name__ == "__main__":
tickers = ["BIL", "AGG", "TIP", "MUB",
"PFF", "IVV", "IWM", "EFA", "EEM", "IYR"]
# start: str = "2023-05-30"
# end: str = "2024-05-30"
# err, names = get_investment_names(tickers)
# if err != "":
# print(err)
# else:
# adj_daily_close = get_adj_daily_close(tickers, start, end)
# print(adj_daily_close.head(10))
# -------------------------------------
# d=get_max_inception_date(["BIL", "MSFT", "DREGX"])
# print(d)
# t=datetime.fromtimestamp(d)
# print(t.strftime('%m/%d/%Y'))
# --------------------------------------
# err, df = get_names_and_inceptions(tickers)
# # df["Inception"] = pd.to_datetime(df["Inception"], unit="s", utc=True).dt.strftime(
# # "%Y-%m-%d"
# # )
# # df["Inception"] = pd.to_datetime(df["Inception"], unit="s", utc=True)
# print(df.info())
# print(df)
# --------------------------------------
# Get latest yield on 10-year Treasury
# end_date = datetime.today()
# start_date = datetime.today()-timedelta(days=7)
# tnx = yf.download(["^TNX"], start=start_date, end=end_date)
# print(tnx)
# rf_rate=tnx.loc[:,"Close"].iloc[-1]
# print(f"rf_rate: {rf_rate:.2f}%")
# --------------------------------------
# Get last price of Ticker
# last_price: float= yf.Ticker('^TNX').info['previousClose']
# pprint(f"last_price: {last_price}")
# --------------------------------------
# Get yield of 10-year Treasury
print(f"10-year Treasury Current Yield: {get_previous_close('^TNX'):2f}%")