def generatePriceConfidence(self, ticker, predictedPE, fileDf): print("\nPrice Confidence Summary for Ticker: " + ticker) mrktData = web.get_quote_yahoo(ticker) mrktData.columns = [ 'P/E', 'Change Percent', 'Current Price', 'Short Ratio', 'Time' ] mrktPrice = mrktData.ix[ticker]['Current Price'] print mrktData upperPredPrice = 0.0 lowerPredPrice = 0.0 mrktEPS = float(fileDf.ix[ticker][CONST_EPS]) mrktMonVolatility = float(fileDf.ix[ticker][CONST_MON_VOLATILITY][:-1]) mrktYrVolatility = mrktMonVolatility * sqrt(12) predictedPrice = predictedPE * mrktEPS print("\nEPS (ttm) = %0.2f" % mrktEPS) print("Volatility (Month) = %0.2f" % mrktMonVolatility + "%") print("Volatility (Year) = %0.2f" % mrktYrVolatility + "%") print("Market Price = %0.2f" % mrktPrice) print("Predicted Price (Mean) = %0.2f" % predictedPrice) confIntVolatility = 1.96 * mrktYrVolatility upperPredPrice = predictedPrice * (1 + confIntVolatility / 100) lowerPredPrice = predictedPrice * (1 - confIntVolatility / 100) print("\tConf Int \t95% or 1.96σ") print("Volatility (Year) \t %0.2f" % confIntVolatility + "%") print("Upper Price \t\t %0.2f" % upperPredPrice) print("Lower Price \t\t %0.2f" % lowerPredPrice) print("\nValuation Summary for Ticker: " + ticker) if mrktPrice >= upperPredPrice: print("\tOver Valued") valPercentage = ((mrktPrice - upperPredPrice) / mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Upper Predicted Price") valPercentage = ((mrktPrice - predictedPrice) / mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice < lowerPredPrice: print("\tUnder Valued") valPercentage = ((lowerPredPrice - mrktPrice) / mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Lower Predicted Price") valPercentage = ((predictedPrice - mrktPrice) / mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice >= predictedPrice: print("\tFairly Valued") valPercentage = ((mrktPrice - predictedPrice) / mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice < predictedPrice: print("\tFairly Valued") valPercentage = ((predictedPrice - mrktPrice) / mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Mean Predicted Price") else: print("Oops ! Something went wrong. Cannot value Ticker : " + ticker)
def snapshot_yahoo_pandas(symbols): ''' Get a simple snapshot from yahoo, return dataframe __________________________________________________ Return pandas.DataFrame with symbols as index and columns = [change_pct, time, last, short_ratio, PE] ''' if isinstance(symbols, str): symbols = [symbols] return get_quote_yahoo(symbols)
def stock(symbol): """ gets last traded price from google for given security """ import pandas.io.data as pd df = pd.get_quote_yahoo(symbol) #print(df) cols = ['PE', 'change_pct', 'last', 'short_ratio', 'time'] result = pd.DataFrame(df, columns=cols) return result.iloc[0]['last']
def stock(symbol): """ gets last traded price from google for given security """ import pandas.io.data as pd df = pd.get_quote_yahoo(symbol) # print(df) cols = ["PE", "change_pct", "last", "short_ratio", "time"] result = pd.DataFrame(df, columns=cols) return result.iloc[0]["last"]
def generatePriceConfidence(self, ticker, predictedPE, fileDf): print("\nPrice Confidence Summary for Ticker: " + ticker) mrktData = web.get_quote_yahoo(ticker) mrktData.columns = ['P/E', 'Change Percent', 'Current Price', 'Short Ratio', 'Time'] mrktPrice = mrktData.ix[ticker]['Current Price'] print mrktData upperPredPrice = 0.0 lowerPredPrice = 0.0 mrktEPS = float(fileDf.ix[ticker][CONST_EPS]) mrktMonVolatility = float(fileDf.ix[ticker][CONST_MON_VOLATILITY][:-1]) mrktYrVolatility = mrktMonVolatility * sqrt(12) predictedPrice = predictedPE * mrktEPS print("\nEPS (ttm) = %0.2f" % mrktEPS) print("Volatility (Month) = %0.2f" % mrktMonVolatility + "%") print("Volatility (Year) = %0.2f" % mrktYrVolatility + "%") print("Market Price = %0.2f" % mrktPrice) print("Predicted Price (Mean) = %0.2f" % predictedPrice) confIntVolatility = 1.96 * mrktYrVolatility upperPredPrice = predictedPrice * (1 + confIntVolatility/100) lowerPredPrice = predictedPrice * (1 - confIntVolatility/100) print("\tConf Int \t95% or 1.96σ") print("Volatility (Year) \t %0.2f" % confIntVolatility + "%") print("Upper Price \t\t %0.2f" % upperPredPrice) print("Lower Price \t\t %0.2f" % lowerPredPrice) print("\nValuation Summary for Ticker: " + ticker) if mrktPrice >= upperPredPrice: print("\tOver Valued") valPercentage = ((mrktPrice - upperPredPrice)/mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Upper Predicted Price") valPercentage = ((mrktPrice - predictedPrice)/mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice < lowerPredPrice: print("\tUnder Valued") valPercentage = ((lowerPredPrice - mrktPrice)/mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Lower Predicted Price") valPercentage = ((predictedPrice - mrktPrice)/mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice >= predictedPrice: print("\tFairly Valued") valPercentage = ((mrktPrice - predictedPrice)/mrktPrice) * 100 print("\tDownside of %0.2f" % valPercentage + "% to Mean Predicted Price") elif mrktPrice < predictedPrice: print("\tFairly Valued") valPercentage = ((predictedPrice - mrktPrice)/mrktPrice) * 100 print("\tUpside of %0.2f" % valPercentage + "% to Mean Predicted Price") else: print("Oops ! Something went wrong. Cannot value Ticker : " +ticker)
def run(self, frequency): while True: self.start_time = datetime.datetime.now() log.info("Scraping Data at %s" % self.start_time) if self.symbols: self.curr_quotes = web.get_quote_yahoo(self.symbols) self.time = datetime.datetime.utcnow() if self.forex_codes: self.curr_forex = self.get_forex(self.forex_codes) log.debug(self.curr_forex) log.debug(self.curr_quotes) log.debug("Difference between times: %s" % (self.time - self.start_time).total_seconds()) self.save_current_data() sleep(frequency - (datetime.datetime.now() - self.start_time).total_seconds())
def run(self, frequency): while True: self.start_time = datetime.datetime.now() log.info("Scraping Data at %s" % self.start_time) if self.symbols: self.curr_quotes = web.get_quote_yahoo(self.symbols) self.time = datetime.datetime.utcnow() if self.forex_codes: self.curr_forex = self.get_forex(self.forex_codes) log.debug(self.curr_forex) log.debug(self.curr_quotes) log.debug("Difference between times: %s" % (self.time - self.start_time).total_seconds()) self.save_current_data() sleep(frequency - (datetime.datetime.now() - self.start_time).total_seconds() )
def test_get_quote_string(self): _yahoo_codes.update({'MarketCap': 'j1'}) df = web.get_quote_yahoo('GOOG') self.assertFalse(pd.isnull(df['MarketCap'][0]))
def test_get_quote_string(self): df = web.get_quote_yahoo('GOOG')
def get_quote(self, symbol): """Retrieve the Quote from Yahoo using pandas""" quote = web.get_quote_yahoo(symbol) if 0 == quote['last'][0]: raise SymbolNotInDB(symbol) return quote
def test_get_quote(self): df = web.get_quote_yahoo(pd.Series(["GOOG", "AAPL", "GOOG"])) assert_series_equal(df.ix[0], df.ix[2])
def get_near_stock_price(self, above_below=2, call=True, put=False, month=None, year=None): """ Cuts the data frame opt_df that is passed in to only take options that are near the current stock price. Parameters ---------- above_below: number, int, optional (default=2) The number of strike prices above and below the stock price that should be taken call: bool Tells the function weather or not it should be using self.calls put: bool Tells the function weather or not it should be using self.puts month: number, int, optional(default=None) The month the options expire. This should be either 1 or 2 digits. year: number, int, optional(default=None) The year the options expire. This sould be a 4 digit int. Returns ------- chopped: DataFrame The resultant DataFrame chopped down to be 2 * above_below + 1 rows desired. If there isn't data as far out as the user has asked for then """ price = float(get_quote_yahoo([self.symbol])['last']) if call: try: if month: m1 = month if len(str(month)) == 2 else '0' + str(month) name = 'calls' + str(m1) + str(year)[2:] df_c = self.__getattribute__(name) else: df_c = self.calls except AttributeError: df_c = self.get_call_data(month, year) # NOTE: For some reason the put commas in all values >1000. We remove # them here df_c.Strike = df_c.Strike.astype(str).apply(lambda x: \ x.replace(',', '')) # Now make sure Strike column has dtype float df_c.Strike = df_c.Strike.astype(float) start_index = np.where(df_c['Strike'] > price)[0][0] get_range = range(start_index - above_below, start_index + above_below + 1) chop_call = df_c.ix[get_range, :] chop_call = chop_call.dropna() chop_call = chop_call.reset_index() if put: try: if month: m1 = month if len(str(month)) == 2 else '0' + str(month) name = 'puts' + str(m1) + str(year)[2:] df_p = self.__getattribute__(name) else: df_p = self.puts except AttributeError: df_p = self.get_put_data(month, year) # NOTE: For some reason the put commas in all values >1000. We remove # them here df_p.Strike = df_p.Strike.astype(str).apply(lambda x: \ x.replace(',', '')) # Now make sure Strike column has dtype float df_p.Strike = df_p.Strike.astype(float) start_index = np.where(df_p.Strike > price)[0][0] get_range = range(start_index - above_below, start_index + above_below + 1) chop_put = df_p.ix[get_range, :] chop_put = chop_put.dropna() chop_put = chop_put.reset_index() if call and put: return [chop_call, chop_put] else: if call: return chop_call else: return chop_put
def get_stock_prices(self): dataframe = get_quote_yahoo([stock for stock in self.stocks_owned]) for stock in self.stocks_owned: self.stocks_owned[stock]['price'] = dataframe.ix[stock]['last']
def test_get_quote_stringlist(self): df = web.get_quote_yahoo(['GOOG', 'AAPL', 'GOOG']) assert_series_equal(df.ix[0], df.ix[2])
def test_get_quote_stringlist(self): df = web.get_quote_yahoo(["GOOG", "AAPL", "GOOG"]) assert_series_equal(df.ix[0], df.ix[2])
# -*- coding: utf-8 -*- """ Created on Thu Dec 4 22:07:12 2014 @author: jmalinchak """ #from pandas.io.data import DataReader #from datetime import datetime #msft = DataReader("MSFT", "yahoo") #print(msft.bid) import pandas.io.data as pd df = pd.get_quote_yahoo('HPQ') #print(df) cols = ['PE', 'change_pct', 'last', 'short_ratio', 'time'] result = pd.DataFrame(df, columns=cols) print(result.iloc[0]['last']) #data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012], # 'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'], # 'wins': [11, 8, 10, 15, 11, 6, 10, 4], # 'losses': [5, 8, 6, 1, 5, 10, 6, 12]} # #football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses']) #print(football) # #from_csv = pd.read_csv('C:\\Documents and Settings\\jmalinchak\\My Documents\\My Python\\Active\inputs\\Options AAPL 2015-01-17 20141203221727.csv') #from_csv.head() #print(from_csv)
import datetime # We will look at stock prices over the past year, starting at January 1, 2016 start = datetime.datetime(2016,1,1) end = datetime.date.today() # Let's get Apple stock data; Apple's ticker symbol is AAPL # First argument is the series we want, second is the source ("yahoo" for Yahoo! Finance), third is the start date, fourth is the end date apple = web.DataReader("AAPL", "yahoo", start, end) type(apple) !pip install pandas_datareader import pandas_datareader.data as web amzn = web.get_quote_yahoo('AMZN') amzn ### API KEY Quandl: import quandl import datetime quandl.ApiConfig.api_key = def quandl_stocks(symbol, start_date=(2000, 1, 1), end_date=None): """ symbol is a string representing a stock symbol, e.g. 'AAPL'
if len(df_optionpricescurrent) == 0: if showresults == 1: print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ got df_optionpricescurrent here') df_optionpricescurrent = pp.options_to_dataframe(symbol,expirationdate_string,0) df_optionpricescurrent['optiontype'] = df_optionpricescurrent['optionsymbol'].to_frame(name='optionsymbol').applymap(optiontype) dict_of_df_optionpricescurrent[symbol+'|'+expirationdate_string] = df_optionpricescurrent else: print('>>>>>>>>>>>>>>>>>>>> already have df_optionpricescurrent') continue df_stockpricecurrent = dict_of_df_stockpricecurrent.get(symbol,dict_empty) if len(df_stockpricecurrent) == 0: #print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ got df_stockpricecurrent here') df_stockpricecurrent = pdata.get_quote_yahoo(symbol) dict_of_df_stockpricecurrent[symbol] = df_stockpricecurrent else: continue #if showresults == 1: #print('>>>>>>>>>>>>>>>>>>>> already have df_stockpricecurrent') stockpricelast = df_stockpricecurrent['last'].iloc[0] stockpricetime = df_stockpricecurrent['time'].iloc[0] print('symbol: '+symbol) #if showresults == 1: # print('stockpricelast',stockpricelast) filepath = os.path.join(myselectedcandidatesfolder,filename) df_00 = pd.read_csv(filepath) df_00['captureopen'] = df_00.sbid - df_00.bask
def test_get_quote_series(self): df = web.get_quote_yahoo(pd.Series(['GOOG', 'AAPL', 'GOOG'])) assert_series_equal(df.ix[0], df.ix[2])
def test_get_quote_string(self): df = web.get_quote_yahoo('GOOG') df2 = web.get_quote_yahoo('GOOG') assert_frame_equal(df, df2)
def test_get_quote(self): df = web.get_quote_yahoo(pd.Series(['GOOG', 'AAPL', 'GOOG'])) assert_series_equal(df.ix[0], df.ix[2])
df_optionpricescurrent = dict_of_df_optionpricescurrent.get(symbol+'|'+expirationdate_string,dict_empty) if len(df_optionpricescurrent) == 0: print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ got df_optionpricescurrent - -',symbol+'|'+expirationdate_string) df_optionpricescurrent = pp.options_to_dataframe(symbol,expirationdate_string,0) df_optionpricescurrent['optiontype'] = df_optionpricescurrent['optionsymbol'].to_frame(name='optionsymbol').applymap(optiontype) dict_of_df_optionpricescurrent[symbol+'|'+expirationdate_string] = df_optionpricescurrent else: print('>>>>>>>>>>>>>>>>>>>> already have df_optionpricescurrent - -',symbol+'|'+expirationdate_string) #continue df_stockpricecurrent = dict_of_df_stockpricecurrent.get(symbol,dict_empty) if len(df_stockpricecurrent) == 0: print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ got df_stockpricecurrent here') df_stockpricecurrent = pdata.get_quote_yahoo(symbol) dict_of_df_stockpricecurrent[symbol] = df_stockpricecurrent else: #continue #if showresults == 1: print('>>>>>>>>>>>>>>>>>>>> already have df_stockpricecurrent - '+symbol) stockpricelast = df_stockpricecurrent['last'].iloc[0] stockpricetime = df_stockpricecurrent['time'].iloc[0] print('symbol: '+symbol) #if showresults == 1: # print('stockpricelast',stockpricelast) filepath = os.path.join(myselectedcandidatesfolder,filename) print(filepath) df_00 = pd.read_csv(filepath)