def calculate_previous_ema(ticker: yf.Ticker, time_period="1mo", days_previous=1) -> float: time_period_days = len(ticker.history(period=time_period)) stock_history = ticker.history(period=time_period) return stock_history.iloc[time_period_days - days_previous - 1].to_dict( )['Close'] * (2.5 / (1 + time_period_days)) + calculate_sma( ticker, time_period) * (1 - (2.5 / (1 + time_period_days)))
def historicaltest(): if request.method == 'GET': obj = '' try: obj = Ticker('msft') except Exception as ex: print(ex) val = '' try: val = obj.history(period='max', interval='1d') val = val.reset_index() except Exception as ex: print(ex) data = dict() data['date'] = val['Date'].astype(str).tolist() data['open'] = val['Open'].tolist() data['high'] = val['High'].tolist() data['low'] = val['Low'].tolist() data['close'] = val['Close'].tolist() data['volume'] = val['Volume'].tolist() for i in range(0, len(data['date'])): year = data['date'][i][:4] month = data['date'][i][5:7] day = data['date'][i][8:] dt = datetime.datetime(int(year), int(month), int(day)) timestamp = int(dt.replace(tzinfo=timezone.utc).timestamp()) data['date'][i] = timestamp outputdata = jsonify(data) outputdata.headers.add("Access-Control-Allow-Origin", "*") return outputdata
def getStock(ticker, time): # get current prices c = Ticker(ticker) t = c.history(time) ans = {} # return based on change a = t.to_dict()["Open"].keys() days = [str(i.to_pydatetime()).split(" ")[0] for i in a] try: c = c.info mc = intword(c['marketCap'], format="%0.3f") inf = ticker + ": " + c["longName"] + "!Sector: " + \ c['sector'] + "!Market Cap: $" + mc except: inf = ticker[1:] + " Index" if t["Close"][-1] > t["Close"][-2]: ans["price"] = "{: .2f}".format(t["Close"][-1]) ans["change"] = "+{:.2f}%".format( (1 - (t["Close"][-2] / t["Close"][-1])) * 100) ans["change"] += " " * (7 - len(ans["change"])) + "⬆" ans["history"] = inf + "|" + str(list(zip(days, t["Close"]))) else: ans["price"] = "{: .2f}".format(t["Close"][-1]) ans["change"] = "-{:.2f}%".format( ((t["Close"][-2] / t["Close"][-1]) - 1) * 100) ans["change"] += " " * (7 - len(ans["change"])) + "⬇" ans["history"] = inf + "|" + str(list(zip(days, t["Close"]))) print(ticker) return ans
def main(): gran = [('2y', '60m'), ('60d', '15m'), ('30d', '5m'), ('7d', '1m')] config = ConfigParser() config.read('/opt/market/market.ini') stocks = config.get('general', 'stocks') db = "postgres://[email protected]:5432/stocks" session = market.session.Session(db) for stock in stocks.split(): print(stock) if session.check_table(stock): continue dfs = list() ticker = Ticker(stock) for period, interval in gran: df = ticker.history(period=period, interval=interval) dfs.append(df) df = pd.concat(dfs) df = market.df.deduplicate(df) session.push_df(dataframe=df, name=stock)
def previous_high(ticker: yf.Ticker, time_period: str) -> float: high = 0 stock_history = ticker.history(time_period) for i in range(0, len(stock_history) - 2): temp_high = stock_history.iloc[i].to_dict()['High'] if temp_high > high: high = temp_high return high
def download_hist(stock_to_download): try: ticker_obj = Ticker(stock_to_download) hist = ticker_obj.history(period="max") hist.to_csv("data/stocks/" + stock_to_download + ".csv") except: error = sys.exc_info()[0] logger.debug("Unable to download historical stock data for: %s %s", stock_to_download, str(error)) raise
def run(self): company = Ticker(self.ticker) if (company == None): return # Get prices using yfinance package. quotes = company.history(period="max") # Save results to csv. with self.output().open("w") as out_file: quotes.to_csv(out_file, index=False, compression="gzip")
def __get_history(self): from yfinance import Ticker from pandas import DataFrame from datetime import datetime, timedelta, date # Get stock data from yfinance module from 60 days before 01/01 to today stock_data = Ticker(self.stock) df = DataFrame(stock_data.history(start=str(datetime.now().date().replace(month=1, day=1) - timedelta(60)), end=str(date.today()))) return df
class EquityYFinance(Asset): def __init__(self, ticker): from yfinance import Ticker super().__init__(ticker, None) self.y = Ticker(ticker) self.h = self.y.history(period="max") def price(self, t: Date) -> float: return self.h.Close[t] def coupon(self, t: Date) -> float: return self.h.Dividends[t]
def calculate_sma(ticker: yf.Ticker, time_period="1mo", interval="1d") -> float: stock_history = ticker.history(period=time_period, interval=interval) summation = 0 time_period_days = 0 for i in range(0, len(stock_history) - 1): summation += stock_history.iloc[i].to_dict()['Close'] time_period_days += 1 if time_period_days > 0: return summation / time_period_days return sys.maxsize
def processHist(ticker: yf.Ticker): hist = {} info = {} data = ticker.history(period='max', interval='5d') data = data.where(pd.notnull(data), None) try: for item in data.T.iteritems(): stuff = dict(item[1]) try: hist[item[0].value] = stuff except Exception as e: hist[item[0]] = stuff except Exception as e: hist['error'] = e return hist
def main(): config = ConfigParser() config.read('/opt/market/market.ini') stocks = config.get('general', 'stocks') db = "postgres://[email protected]:5432/stocks" session = market.session.Session(db) for stock in stocks.split(): print(stock) if not session.check_table(stock): continue ticker = Ticker(stock) df = ticker.history(period='15m', interval='1m') session.push_df(dataframe=df, name=stock)
def historical(): if request.method == 'POST': data = json.loads(request.data) stock = str(data['stock']) period = str(data['period']) interval = str(data['interval']) obj = '' try: obj = Ticker(stock) except Exception as ex: print(ex) val = '' try: val = obj.history(period=period, interval=interval) val = val.reset_index() except Exception as ex: print(ex) data = dict() data['date'] = val['Date'].astype(str).tolist() data['open'] = val['Open'].tolist() data['high'] = val['High'].tolist() data['low'] = val['Low'].tolist() data['close'] = val['Close'].tolist() data['volume'] = val['Volume'].tolist() for i in range(0, len(data['date'])): year = data['date'][i][:4] month = data['date'][i][5:7] day = data['date'][i][8:] dt = datetime.datetime(int(year), int(month), int(day)) timestamp = int(dt.replace(tzinfo=timezone.utc).timestamp()) data['date'][i] = timestamp outputdata = jsonify(data) #outputdata.headers.add("Access-Control-Allow-Origin", "*") #outputdata.headers.add("Access-Control-Allow-Headers", "*") #outputdata.headers.add("Access-Control-Allow-Methods", "*") return outputdata
def get_direction(ticker: yf.Ticker) -> float: stock_history = ticker.history(period="1d", interval="1m") return (stock_history.iloc[len(stock_history) - 1].to_dict()['Close'] - stock_history.iloc[len(stock_history) - 2].to_dict()['Close'] ) / stock_history.iloc[len(stock_history) - 2].to_dict()['Close']
def get_high2current_price_change_percent(ticker: yf.Ticker) -> float: stock_info = ticker.history("1d").iloc[0].to_dict() return (stock_info['Close'] - stock_info['High']) / stock_info['High']
def calculate_ema(ticker: yf.Ticker, time_period="1mo") -> float: stock_history = ticker.history(period=time_period) return stock_history.iloc[len(stock_history) - 1].to_dict()['Close'] * ( 2.5 / (1 + len(stock_history))) + calculate_sma( ticker, time_period) * (1 - (2.5 / (1 + len(stock_history))))
def get_stock_state(ticker: yf.Ticker) -> {}: stock_info = ticker.history("1d").iloc[0].to_dict() stock_info['Time'] = datetime.now().strftime("%H:%M:%S") del stock_info['Dividends'] del stock_info['Stock Splits'] return stock_info
def get_historical_stonk_price_in_usd(stonk: yf.Ticker): price_data = stonk.history(start='2013-10-01') return price_data
def get_stonk_price_since_date_in_usd(stonk: yf.Ticker, since_date: datetime.datetime): price_data = stonk.history(start=since_date.strftime('%Y-%m-%d')) return price_data