def get_options_dict(ticker_list,warm_dict=None): if not warm_dict: tdict={} else: tdict=warm_dict for ticker in ticker_list: if not tdict.has_key(ticker): print '****\n****\n**** getting for %s\n****\n****' % ticker op = Options(ticker, 'yahoo') try: data = op.get_all_data() up = op.underlying_price time.sleep(1200) tdict[ticker]={'data':data,'up':up} except pd.io.data.RemoteDataError: print'Request Refused, Dumping and Exiting...' cPickle.dump(tdict,open('warm_dict.pkl','wb')) sys.exit(0) return tdict
def get_options(sym, expiry, above_below=0): opt = Options(sym, 'yahoo') now = datetime.datetime.now() opt_data = opt.get_options_data(expiry=expiry) if (above_below > 0): opt_data = opt.get_near_stock_price(expiry=expiry, put=True, above_below=above_below) now2 = datetime.datetime.now() print 'get_options():', now2-now return (now2, opt_data)
def __validate_source_connection__(self): """ Check internet connection """ test_stock = 'AAPL' try: aapl = Options(test_stock, self.source) data = aapl.get_all_data() return True except Exception: return False
def __validate_source_connection__(self): """ Check internet connection """ test_stock='AAPL' try: aapl = Options(test_stock, self.source) data = aapl.get_all_data() return True except Exception: return False
def retrieve_option_chain(ticker="SPY"): spy_data = pandas.DataFrame() print(" --> Today's option chain not on system: downloading it now... ") try: spy_options = Options(ticker, "yahoo") spy_data = spy_options.get_all_data() spy_data = spy_data.reset_index() if "Symbol" in spy_data.keys(): spy_data = spy_data.set_index("Symbol") spy_data.to_csv(filename, date_format="%Y-%m-%d") # Load the data from the CSV you just wrote # (this ensures that re-shaping is always done # by retrieve_option_chain_from_file() ) spy_data = retrieve_option_chain_from_file(filename) except: print("Error with retrieving data. Please double-check the ticker symbol") return spy_data return spy_data
def pull_data(self, ticket_list): """ Pull online option data :param ticket_list: list contains tickets you want to download :return: option data dict, in the form of [ ticket : DataFrame, ... ] """ if isinstance(ticket_list, str): ticket_list = (ticket_list, ) option_dict = {} for ticket in ticket_list: print "Pull Option Data : %s ..." % ticket try: option_method = Options(ticket, self.source) option_dict[ticket] = option_method.get_all_data() if len(option_dict[ticket]) == 0: print "Length of data is Zero during the time asked" except Exception as err_message: option_dict[ticket] = None print "Exception: %s" % err_message # raise RuntimeError("Can't not download Stock: %s" % stock) return option_dict
# pick a recent date and subtract seven days to be sure we get a quote # http://pymotw.com/2/datetime/#date-arithmetic today = dt.date.today() one_week = dt.timedelta(days=7) start = today - one_week stock = web.DataReader(ticker, 'yahoo', start) print(stock.tail()) # just to see what we have # take the last close (that's what the -1 does) atm = stock.ix[-1,'Close'] # the -1 takes the last observation #%% # get option prices for same ticker # http://pandas.pydata.org/pandas-docs/stable/remote_data.html#yahoo-finance-options option = Options(ticker, 'yahoo') expiry = dt.date(2014, 12, 20) data_calls = option.get_call_data(expiry=expiry) data_puts = option.get_put_data(expiry=expiry) print(data_calls.tail()) print(data_puts.tail()) #%% # plot puts v strike, call v strike calls_bid = data_calls['Bid'] calls_ask = data_calls['Ask'] calls_strikes = data_calls['Strike'] calls_mid = (data_calls['Bid'] + data_calls['Ask'])/2
def get_option_data(self, symbol): aapl = Options(symbol, 'google') data = aapl.get_all_data() return data
from pandas.io.data import Options import datetime aapl = Options('AAPL', 'yahoo') expiry = datetime.date(2014, 5, 1) aapl.get_call_data(expiry=expiry)
for i in range(10000): sigma=0.0001*(i+1) d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) d2 = d1-sigma*sqrt(T) c2=S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2) abs_diff=abs(c2-c) #print 'i=',i,'c=', c,'c2=',c2,'abs_diff=',abs_diff,'min_value=',min_value if abs_diff<min_value: min_value=abs_diff implied_vol=sigma k=i return implied_vol ticker='IBM' m=2 y=2014 s=185.08 r=0.0003 T=2./12.0 x = Options(ticker,'yahoo') puts,calls = x.get_options_data(month=m,year=y) print 'done' n=len(calls.Strike) for i in range(n): x=calls.Strike[i] c=(calls.Bid[i]+calls.Ask[i])/2.0 if c >0: vol=implied_vol_call_min(s,x,T,r,c) print x,c,vol
# -*- coding: utf-8 -*- """ Created on Thu Jul 16 18:02:31 2015 @author: justin.malinchak """ #import pullprices_optionsonly as pp # #pp.options('VIX', # '2015-07-17', # 'c:\\Batches\\$Work') from pandas.io.data import Options temp = Options('SPY','yahoo') z = temp.get_options_data(7,2014) print z
def get_option_data(tickrr, exp_date): x = Options(ticker, 'yahoo') puts, calls = x.get_options_data(expiry=exp_date) return puts, calls
>>> implied_vol_call(40,40,1.,0.1,5.31) (39, 0.2, 0.0021293661356418525) >>> """ from scipy import log, exp, sqrt, stats for i in range(200): sigma = 0.005 * (i + 1) d1 = (log(S / X) + (r + sigma * sigma / 2.) * T) / (sigma * sqrt(T)) d2 = d1 - sigma * sqrt(T) diff = c - (S * stats.norm.cdf(d1) - X * exp(-r * T) * stats.norm.cdf(d2)) if abs(diff) <= 0.01: return sigma ticker = 'IBM' m = 2 y = 2014 s = 185.08 x = Options(ticker, 'yahoo') calls, puts = x.get_options_data(month=m, year=y) print 'done' n = len(calls.Strike) for i in range(n): x = calls.Strike[i] c = (calls.Bid[i] + calls.Ask[i]) / 2.0 if c > 0: vol = implied_vol_call(s, x, 2. / 12., 0.03, c) print x, c, vol
from pandas.io.data import Options import datetime as dt #import matplotlib.pylab as plt # ticker ticker = 'spy' today = dt.date.today() one_week = dt.timedelta(days=7) start = today - one_week stock = web.DataReader(ticker, 'yahoo', start) # take the last close (-1 is the last, 'Close' is the close) atm = stock.ix[-1, 'Close'] # the -1 takes the last observation print('Stock price (at the money): ', atm) # get option prices for same ticker option = Options(ticker, 'yahoo') expiry = dt.date(2016, 2, 19) #data_calls = option.get_call_data(expiry=expiry).dropna() #data_puts = option.get_put_data(expiry=expiry).dropna() # compute mid of bid and ask and arrange series for plotting calls_bid = data_calls['Bid'] calls_ask = data_calls['Ask'] calls_strikes = data_calls['Strike'] calls_mid = (data_calls['Bid'] + data_calls['Ask']) / 2 puts_strikes = data_puts['Strike'] puts_mid = (data_puts['Bid'] + data_puts['Ask']) / 2 # plot call and put prices v strike plt.plot(calls_strikes, calls_mid, 'r', lw=2, label='calls')
def get_option_data(tickrr,exp_date): x = Options(ticker,'yahoo') puts,calls = x.get_options_data(expiry=exp_date) return puts, calls
""" Name : 4375OS_10_33_option_data_Yahoo.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : [email protected] [email protected] """ from pandas.io.data import Options x = Options('IBM','yahoo') puts,calls = x.get_options_data() print calls.head()
# pick a recent date and subtract seven days to be sure we get a quote # http://pymotw.com/2/datetime/#date-arithmetic today = dt.date.today() one_week = dt.timedelta(days=7) start = today - one_week stock = web.DataReader(ticker, 'yahoo', start) print(stock.tail()) # just to see what we have # take the last close (that's what the -1 does) atm = stock.ix[-1, 'Close'] # the -1 takes the last observation #%% # get option prices for same ticker # http://pandas.pydata.org/pandas-docs/stable/remote_data.html#yahoo-finance-options option = Options(ticker, 'yahoo') expiry = dt.date(2014, 12, 20) data_calls = option.get_call_data(expiry=expiry) data_puts = option.get_put_data(expiry=expiry) print(data_calls.tail()) print(data_puts.tail()) #%% # plot puts v strike, call v strike calls_bid = data_calls['Bid'] calls_ask = data_calls['Ask'] calls_strikes = data_calls['Strike'] calls_mid = (data_calls['Bid'] + data_calls['Ask']) / 2
def call_data(tickrr,exp_date): x = Options(ticker,'yahoo') data= x.get_call_data(expiry=exp_date) return data
startTickerIndex = 0 if startTickerIndex >= len(tickersList): startTickerIndex = 0 for i in range(startTickerIndex, len(tickersList)): ticker = tickersList[i] if ticker in downloaded: print "Already downloaded",ticker," ... Skipping." continue print "Downloading", ticker, "...", # download the data toDownload = Options(ticker, "yahoo") try: data = toDownload.get_options_data(); pd.DataFrame(data).to_csv(baseDir+"/data/" + ticker) print "done." except (ValueError, RemoteDataError, StopIteration) as e: print "skipped." print e downloaded.add(ticker) last = open(baseDir+"last-downloaded", "w") if i != len(tickersList) - 1: last.write(ticker) last.close() time.sleep(0.1)
""" Name : 4375OS_10_33_option_data_Yahoo.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : [email protected] [email protected] """ from pandas.io.data import Options x = Options('IBM', 'yahoo') puts, calls = x.get_options_data() print calls.head()
start = dt.datetime(2015, 1, 1) msi = web.DataReader('msi', 'yahoo', start) msi['Close'].plot() #%% """ Options data -- doesn't work http://pandas.pydata.org/pandas-docs/stable/remote_data.html#yahoo-finance-options """ import pandas as pd print('Pandas version:', pd.__version__) from pandas.io.data import Options aapl = Options('aapl', 'yahoo') data = aapl.get_all_data() #%% """ convert do file to pandas format and variable labels CPS http://www.nber.org/data/cps_progs.html MEPS http://meps.ahrq.gov/mepsweb/data_stats/download_data_files_detail.jsp?cboPufNumber=HC-155 """ import pandas as pd url = 'http://www.nber.org/data/progs/cps/cpsmar2014.dct' pd.read_csv(url, sep='\s+') #open(url).read()
# -*- coding: utf-8 -*- """ Created on Thu Jul 16 18:02:31 2015 @author: justin.malinchak """ #import pullprices_optionsonly as pp # #pp.options('VIX', # '2015-07-17', # 'c:\\Batches\\$Work') from pandas.io.data import Options temp = Options('SPY', 'yahoo') z = temp.get_options_data(7, 2014) print z
from pandas.io.data import Options spy = Options('spy', 'yahoo') chain = spy.get_all_data()
import time import math t1 = time.time() options = pd.read_csv("options.csv") tickers = options['Symbol'] #tickers=['GNW','MBI','VLO','BP'] yahoo_cap_url = 'http://finance.yahoo.com/d/quotes.csv?s=' bank_roll = 14000 offers = [] for e in tickers: expiry_2 = (2018, 1) expiry_1 = (2017, 1) tick = Options(e, 'yahoo') try: frame = tick.get_call_data(month=expiry_2[1], year=expiry_2[0]) a = list(frame.index) except: try: frame = tick.get_call_data(month=expiry_1[1], year=expiry_1[0]) a = list(frame.index) except: print e pass strike = [] for e in a: strike.append(e[0]) frame['Strike'] = strike
def get_straddle(): options = Options("AAPL", "yahoo") call = get_price(options, True, False) put = get_price(options, False, True) return call + put
options.rror.iloc[i] = (p / -l) options = options.drop(['sv', 'lv'], axis = 1) return options ############################################################################### # Calculate Best Options for multiple indexes and secruities ############################################################################### securities = ['spy', 'iwm', 'qqq', 'aapl', 'nflx', 'kmx'] for s in securities: try: opt = Options(s, 'yahoo') today = datetime.datetime.today() today = datetime.date(today.year, today.month, today.day) for e in opt.expiry_dates: if (e - today).days > 4 and (e - today).days < 15: expiry = e call = opt.get_call_data(expiry=expiry) price = call.Underlying_Price[0] prices, p = cdf(s, expiry, price)
def call_data(tickrr, exp_date): x = Options(ticker, 'yahoo') data = x.get_call_data(expiry=exp_date) return data
""" """ the usual checks """ import sys import pandas as pd print('\nPython version: ', sys.version) print('\nPandas version: ', pd.__version__, '\n') #%% """ Remote data access """ from pandas.io.data import Options aapl = Options('aapl', 'yahoo') data = aapl.get_all_data() #%% """ Set up simple dataframes to play with """ # create arbitrary dataframe gdp = [2, 5, 7, 9] pop = [9, 6, 3, 10] cty = ['USA', 'USA', 'FRA', 'FRA'] year = ['2010', '2011', '2012', '2013'] data = {'gdp': gdp, 'pop': pop, 'cty': cty}
""" Name : 4375OS_10_34_get_option_data_given_year_month.py Book : Python for Finance Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 12/26/2013 email : [email protected] [email protected] """ from pandas.io.data import Options ticker='IBM' month=2 year=2014 x = Options(ticker,'yahoo') puts,calls = x.get_options_data(month,year) print puts.head()
from pandas.io.data import Options aapl = Options('AAPL') vals = aapl.get_options_data() print(vals)
import pandas as pd, datetime from pandas_datareader import data # Stocks start=datetime.datetime(2013, 1, 1) end=datetime.datetime(2015, 9, 30) s = data.DataReader("SSW", 'yahoo', start, end) print s.head() # Options from pandas.io.data import Options aapl = Options('AAPL',"yahoo") df = aapl.get_options_data() print df.head()
options.rror.iloc[i] = (p / -l) options = options.drop(['sv', 'lv'], axis=1) return options ############################################################################### # Calculate Best Options for multiple indexes and secruities ############################################################################### securities = ['spy', 'iwm', 'qqq', 'aapl', 'nflx', 'kmx'] for s in securities: try: opt = Options(s, 'yahoo') today = datetime.datetime.today() today = datetime.date(today.year, today.month, today.day) for e in opt.expiry_dates: if (e - today).days > 4 and (e - today).days < 15: expiry = e call = opt.get_call_data(expiry=expiry) price = call.Underlying_Price[0] prices, p = cdf(s, expiry, price) bull = bull_call_spread() if bull.empty: