Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
webbrowser.get().open(url)
speak(f'Here is what I found for {search_term} on youtube')
# 7: get stock price
if there_exists(["price of"]):
search_term = voice_data.lower().split(" of ")[-1].strip() #strip removes whitespace after/before a term in string
stocks = {
"apple":"AAPL",
"microsoft":"MSFT",
"facebook":"FB",
"tesla":"TSLA",
"bitcoin":"BTC-USD"
}
try:
stock = stocks[search_term]
stock = yf.Ticker(stock)
price = stock.info["regularMarketPrice"]
speak(f'price of {search_term} is {price} {stock.info["currency"]} {person_obj.name}')
except:
speak('oops, something went wrong')
if there_exists(["exit", "quit", "goodbye"]):
speak("going offline")
exit()
self._info['logo_url'] = ""
try:
domain = self._info['website'].split(
'://')[1].split('/')[0].replace('www.', '')
self._info['logo_url'] = 'https://logo.clearbit.com/%s' % domain
except Exception:
pass
# events
try:
cal = _pd.DataFrame(
data['calendarEvents']['earnings'])
cal['earningsDate'] = _pd.to_datetime(
cal['earningsDate'], unit='s')
self._calendar = cal.T
self._calendar.index = utils.camel2title(self._calendar.index)
self._calendar.columns = ['Value']
except Exception:
pass
# analyst recommendations
try:
rec = _pd.DataFrame(
data['upgradeDowngradeHistory']['history'])
rec['earningsDate'] = _pd.to_datetime(
rec['epochGradeDate'], unit='s')
rec.set_index('earningsDate', inplace=True)
rec.index.name = 'Date'
rec.columns = utils.camel2title(rec.columns)
self._recommendations = rec[[
'Firm', 'To Grade', 'From Grade', 'Action']].sort_index()
except Exception:
lines = []
last_refresh = None
today = datetime.date.today()
if os.path.exists(self.currencies_file):
with open(self.currencies_file, 'rt') as cf:
lines = cf.readlines()
if len(lines) > 0 and lines[0].startswith('# date:'):
last_refresh = lines[0].split(':')[1].strip()
last_refresh = datetime.datetime.strptime(last_refresh, '%Y-%m-%d').date()
if not last_refresh or last_refresh != today:
import yfinance
rates = yfinance.get_rates(CURRENCIES)
with open(self.currencies_file, 'wt') as cf:
cf.write('# date: ' + today.strftime('%Y-%m-%d') + '\n')
cf.write('USD = [currency] = usd\n')
for k, v in rates.items():
cf.write('{0} = USD / {1} = {2}\n'.format(k, v, k.lower()))
def get_prices(
self, market: Market, interval: Interval, data_range: int
) -> MarketHistory:
self._wait_before_call(self._config.get_yfinance_api_timeout())
ticker = yf.Ticker(self._format_market_id(market.id))
# TODO check data_range and fetch only necessary data
data = ticker.history(
period="max", interval=self._to_yf_interval(interval).value
)
# Reverse dataframe to have most recent data at the top
data = data.iloc[::-1]
history = MarketHistory(
market,
data.index,
data["High"].values,
data["Low"].values,
data["Close"].values,
data["Volume"].values,
)
return history
continue
predicted_value = predictor.get_prediction(diff)
ticker = fc.getTickerFromCik(cik)
# print('cik: ', cik)
# print('ticker: ', ticker)
# print('current_date.hour: ', current_date.hour)
# print('days_since_last_filing: ', days_since_last_filing)
# print(diff[:100])
# print('predicted_value: ', predicted_value)
if predicted_value == 0:
try:
price = yf.Ticker(ticker).info['regularMarketPreviousClose']
except Exception as e:
print(e)
continue
quantity_to_buy = int(1000 / price)
print(ticker, quantity_to_buy)
if api.get_asset(ticker).tradable:
submitShort(api, ticker, quantity_to_buy)
print('length: ', len(diff))
except Exception as e:
print(e)
continue
def load(ticker_str):
ticker_str = ticker_str.upper()
ticker = yf.Ticker(ticker_str)
try:
data = ticker.info
except ValueError:
return None
history = ticker.history(period="1d")
current_price = history["Close"][0]
change = current_price - data["previousClose"]
change_percent = (change / data["previousClose"]) * 100
pile = urwid.Pile(
[
urwid.Text("STOCKI: The CLI Interface for fetching stock market data\n", align="center"),
urwid.Text(("title", "{} OVERVIEW".format(ticker_str))),
def download_returns(ticker, period="max"):
if isinstance(period, _pd.DatetimeIndex):
p = {"start": period[0]}
else:
p = {"period": period}
return _yf.Ticker(ticker).history(**p)['Close'].pct_change()
def load_quotes(asset):
return yfinance.download(asset)
def download_daily(self, market_data_request):
logger = LoggerManager().getLogger(__name__)
trials = 0
data_frame = None
ticker_list = ' '.join(market_data_request.tickers)
data_frame = yf.download(ticker_list, start=market_data_request.start_date, end=market_data_request.finish_date)
while (trials < 5):
try:
data_frame = yf.download(ticker_list, start=market_data_request.start_date, end=market_data_request.finish_date)
break
except Exception as e:
print(str(e))
trials = trials + 1
logger.info("Attempting... " + str(trials) + " request to download from Yahoo")
if trials == 5:
logger.error("Couldn't download from ONS after several attempts!")
def load_quotes(asset):
return yfinance.download(asset)