示例#1
0
def main2():
    m = stockMongo()
    prices = []
    try:
        dates = options.get_expiration_dates('AAPL')
        try:
            prices = options.get_options_chain('AAPL', dates[14])
            price_calls = pd.DataFrame.from_dict(prices['calls'])
            price_puts = pd.DataFrame.from_dict(prices['puts'])
            strike_date = datetime.datetime.strptime(dates[14], '%B %d, %Y')
            price_calls['strike-date'] = strike_date
            price_puts['strike-date'] = strike_date
            now = datetime.datetime.now()
            #now = datetime.datetime.strptime(now.strftime("%m/%d/%Y"),"%m/%d/%Y")
            price_puts['date'] = now
            price_calls['date'] = now
            price_calls['type'] = 'call'
            price_puts['type'] = 'put'
            m = stockMongo()
            m.update_options('AAPL', price_calls, now, 'call')
            m.update_options('AAPL', price_puts, now, 'put')
            print("Options updated and stored")
        except:
            print("no prices")
    except:
        print("No date")
示例#2
0
def main():
    print("getting symbols")
    m = stockMongo()
    symbols = m.get_symbols()
    tickers = []
    for sym in symbols:
        tickers.append(sym['sym'])
    print("running data collection")
    fails = []
    for tick in tickers:
        try:
            dates = options.get_expiration_dates(tick)
            if len(dates) == 0:
                print(tick + " has no optiondates")
                if len(tickers) < 2:
                    time.sleep(180)
                else:
                    time.sleep(60)
                tickers.append(tick)
                #m = stockMongo()
                #m.remove(tick)
            for day in dates:
                val = collect_options(tick, day)
                if not val:
                    fails.append(tick)
            time.sleep(60)
        except:
            print(tick)
    print(tick)
示例#3
0
    def get_options_expirations(self):

        if not self.live_prices_released():
            filename = 'Chains/' + self.ticker + '_' + 'expirations.pickle'
            expirations = pickle.load(open(filename, "rb"))
        else:
            expirations = options.get_expiration_dates(self.ticker)
        return [{"label": i, "value": i} for i in expirations]
def daily_options_calc(target_folder, tickers):
    #first change all tickers to uppercase
    tickers = [i.upper() for i in tickers]
    #first check to make sure all tickers are valid:
    for t in tickers:
        try:
            si.get_live_price(t)
        except:
            print('')
        
    #each ticker will have a separate excel file/collection of databases corresponding with a ticker
    historical_loc = target_folder
    #FIRST GET LIST OF TICKERS WITH DATA ALREADY COLLECTED, INTERSECT WITH LIST OF TICKERS REQUESTED
    existing_tickers = [i[0:i.index('.')] for i in os.listdir(historical_loc)]
    
    new_tickers = [i for i in tickers if i not in existing_tickers]    
    rate = stock_options.get_current_risk_free_interest_rate()/100
    date_today = datetime.datetime.today()
    date_today = '{}-{}-{}'.format(date_today.month, date_today.day, date_today.year)
    for t in existing_tickers:
        print('updating {}'.format(t))
        #stock price for today
        stock_price = si.get_live_price(t)
        #all expiration dates
        all_dates = options.get_expiration_dates(t)
        
        existing_dates = pd.ExcelFile(historical_loc+t+'.xlsx').sheet_names
        
        new_dates = [i for i in all_dates if i not in existing_dates]
        #first get list of tabs available
        #each date will correspond with a differnt tab in excel sheet/ different table/ different database
        print('updating options information on existing dates')
        existing_dates_calc(existing_dates, stock_price, date_today, rate,historical_loc, t)
        if len(new_dates)>0:
            print('getting values for new options on new dates')        
            new_dates_calc(new_dates, stock_price, date_today,rate,historical_loc, t)
    
    for t in new_tickers:
        print('new file for {}'.format(t))
        stock_price = si.get_live_price(t)
        all_dates = options.get_expiration_dates(t)
        new_dates_calc(all_dates, stock_price, date_today, rate, historical_loc, t)
    
    return 
示例#5
0
 def DataExtraction(a,p):
     dates = options.get_expiration_dates(a)
     date = dates[p]
     newdate = DateConvert(date)
     data_chain1 = options.get_options_chain(a, newdate) 
     for i in (data_chain1["calls"]["Contract Name"]):
             xlist.append("20"+i[4:10])
     for i in (data_chain1["calls"]["Implied Volatility"]):
             ylist.append(i)
     for i in (data_chain1["calls"]["Strike"]):
             zlist.append(i)
示例#6
0
def main2(tick):
    dates = options.get_expiration_dates(tick)
    if len(dates) == 0:
        print(tick + " has no dates")
        #m = stockMongo()
        #m.remove(tick)
    for day in dates:
        val = collect_options(tick, day)
        if not val:
            print("Options where note stored")
    print(tick)
def find_optionable_stocks(udlying):
    """
    Check if the ticker is expired and add it to Global optional list
    :param udlying:  Input Ticket
    :return:  None
    """
    global optionable_list

    g = options.get_expiration_dates(udlying)
    if len(g):
        print(udlying)
        optionable_list.append(udlying)
示例#8
0
async def find_optoinable_stocks_async(udlying):
    """
    Async verion of find_optionable_stocks
    Check if the ticker is expired and add it to Global optional list
    :param udlying: Input tickets
    :return: None
    """
    global optionable_list

    g = options.get_expiration_dates(udlying)
    if g:
        print(udlying)
        optionable_list.append(udlying)
示例#9
0
def get_all_calls(ticker: str) -> pd.DataFrame:
    dates = yo.get_expiration_dates(ticker)
    dates = [dt.strptime(da, c.YAHOO_DATE_FMT) for da in dates]
    log.info(f'Calls found for {ticker} with dates: {dates}')
    calls_df = pd.concat(
        {
            da: yo.get_calls(ticker=ticker, date=da).set_index('Contract Name')
            for da in dates
        },
        0,
        names=['Date', 'Contract Name'])

    return calls_df
示例#10
0
def check():

    for stock, premium in premium_stock.items():
        period = 3
        price = si.get_live_price(stock)

        print("Stock %s, price = %.2f, premium= %.2f " %
              (stock, price, premium))

        expire_dates = ops.get_expiration_dates(stock)
        for date in expire_dates:

            period -= 1
            if period < 0:
                break

            options = ops.get_options_chain(stock, date)
            start = price * 1.05
            print(
                "Checking Call option for %s premium %f for range from %0.1f" %
                (date, premium, start))

            calls = options["calls"]
            selected = calls.loc[(calls['Last Price'] > premium)
                                 & (calls['Strike'] > start) &
                                 (calls['Strike'] < start * 1.5)]
            for ind in selected.index:
                print(
                    " Strike: %s %s Last: %s Bid: %s Ask: %s Volume: %s OI: %s "
                    % (selected['Strike'][ind], selected['Contract Name'][ind],
                       selected['Last Price'][ind], selected['Bid'][ind],
                       selected['Ask'][ind], selected['Volume'][ind],
                       selected['Open Interest'][ind]))

            start = price * 0.95

            print(
                "Checking Put option for %s premium %f for range from %0.1f " %
                (date, premium, start))

            puts = options["puts"]
            selected = puts.loc[(puts['Last Price'] > premium)
                                & (puts['Strike'] < start) &
                                (puts['Strike'] > start * .5)]
            for ind in selected.index:
                print(
                    " Strike: %s %s Last: %s Bid: %s Ask: %s Volume: %s OI: %s "
                    % (selected['Strike'][ind], selected['Contract Name'][ind],
                       selected['Last Price'][ind], selected['Bid'][ind],
                       selected['Ask'][ind], selected['Volume'][ind],
                       selected['Open Interest'][ind]))
def getOptions(ticker):
    dates = options.get_expiration_dates(
        ticker)  # get available expiration dates
    calls = {}
    puts = {}
    for date in dates:  # pull and format data
        if (parse(date) - datetime.now()).days > 60 and (
                parse(date) - datetime.now()).days < 150:
            print(date)
            calls[date] = options.get_options_chain(ticker)['calls'].set_index(
                'Strike')
            puts[date] = options.get_options_chain(ticker)['puts'].set_index(
                'Strike')

    return {'calls': calls, 'puts': puts}
示例#12
0
def main():
    print("getting symbols")
    m = stockMongo()
    symbols = m.get_symbols()
    tickers = []
    for sym in symbols:
        tickers.append(sym['sym'])
    print("running data collection")
    for tick in tickers:
        dates = options.get_expiration_dates(tick)
        if len(dates) == 0:
            m = stockMongo()
            #m.remove(tick)
        for day in dates:
            collect_options(tick, day)
示例#13
0
 def update(self, new_ticker, rate):
     old_ticker = self.ticker
     self.risk_free_rate = rate / 100
     self.ticker = new_ticker.upper()
     if (self.ticker != '') & (new_ticker != old_ticker):
         self.current_price = si.get_live_price(self.ticker)
         self.todays_times = [
             datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")[11:]
         ]
         self.prices_today = [si.get_live_price(self.ticker)]
         self.historical = si.get_data(self.ticker)
         self.option_dates = options.get_expiration_dates(new_ticker)
         self.observed_options = {}
         try:
             self.stats = si.get_stats(self.ticker).to_dict('records')
         except ValueError:
             self.stats = [{
                 'Attribute': 'none available',
                 'Value': 'none available'
             }]
示例#14
0
def expiries(ticker):
    '''
	Gets all maturities for options on a desired stock
	Inputs:
		ticker: (str) Stock or ETF ticker symbol
	Returns:
		expiries: (list) List of all maturities 
	'''
    expiries = options.get_expiration_dates(ticker)
    expiries = [x.replace(',', "") for x in expiries]
    for i, date in enumerate(expiries):
        m, d, y = date.split(" ")
        if len(d) == 1: d = "0" + d
        date = " ".join([m, d, y])
        t = time.strptime(date, "%B %d %Y")
        m, d, y = str(t.tm_mon), str(t.tm_mday), str(t.tm_year)
        if len(m) == 1: m = "0" + m
        if len(d) == 1: d = "0" + d
        date = "-".join([y, m, d])
        expiries[i] = date
    return expiries
示例#15
0
def get_exp_date(ticker):
    exp_date = options.get_expiration_dates(ticker)
    print(exp_date)
    return exp_date
示例#16
0
def populate_dates(ticker):
    all_dates = options.get_expiration_dates(ticker)
    dates = []
    for date in all_dates:
        dates.append({'label': date, 'value': date})
    return dates
示例#17
0
all = sp500 + nasdaq + dow

# remove below line if you uncomment above
# random_ticker = "T"
# setting random strike price to inital value 0
random_strike_price = 0
# exp_dates = []
random_ticker = ""
# random_ticker = random.choice(all)
# exp_dates = options.get_expiration_dates(random_ticker)

# get expiration dates, rerun of randomly chosen stock does not have options
while True:
    random_ticker = random.choice(all)
    exp_dates = options.get_expiration_dates(random_ticker)
    if (len(exp_dates) != 0):
        break

# print("\n" + str(exp_dates))
random_date = random.choice(exp_dates)

# get current price, will be used to make OTM call/put calculation
current_price = si.get_live_price(random_ticker)

# randomly select calls or puts
random_option_type = random.choice(["Call", "Put"])
if (random_option_type == "Call"):
    # random OTM call strike price
    random_strike_price = round(
        random.uniform(current_price, current_price *
示例#18
0
# CALL Option: Right but not obligation to BUY a certain asset up to a certain date.
# PUT Option: Right but not obligation to SELL a certain asset up to a certain date.

from yahoo_fin import options
import pandas as pd

stock = 'MSFT'  # Selected Stock Ticker

print(f'All Expiration Dates for {stock}: ')
print(options.get_expiration_dates(stock))  # Get all possible expiration dates
print('\n')

pd.set_option('display.max_columns', None)  # View all columns
chain = options.get_options_chain(
    stock,
    'August 20, 2021')  # Give all options that expire before a particular date
#print(chain)                # All Options
#print('\n')
print('CALL Options: \n')
print(chain['calls'])  # CALL Options
print('\n')
print('PUT Options: \n')
print(chain['puts'])  # PUT Options
print('\n')

# Another way to get call and put options directly
chain = options.get_calls(stock, 'August 20, 2021')
#print(chain)

# Strike value depends on Stock's price, so modify as per requirement.
print('CALL Options: Strike <=150 \n')
示例#19
0
    'open_interest', 'last_trade_date', 'last_trade_days'
]
column_order = [
    'ul_price', 'days', 'put_call', 'strike', 'opt_price', 'opt_timeval',
    'opt_innerval', 'beven_price', 'beven_pct', 'yield_max', 'yield_pa',
    'ul_ymax', 'imp_vola', 'opt_pr_pct'
]

# -----------------
# main part
# -----------------

ul_price = si.get_live_price(symbol).round(1)

# get option chain first
l = options.get_expiration_dates(symbol)
count = 0
df = pd.DataFrame()

# extract option chains by expiration dates

for x in l:
    count = count + 1
    if count >= 0 and count <= 100:
        df_calls = pd.DataFrame()
        df_puts = pd.DataFrame()
        try:
            expiration = datetime.strptime(x, "%B %d, %Y").strftime('%d/%m/%Y')
            da = options.get_options_chain(symbol, expiration)
            df_calls = df_calls.append(pd.DataFrame(da['calls']),
                                       ignore_index=True)
示例#20
0
def getOptionExpirationDates(ticker):
    expireyLst = options.get_expiration_dates(ticker)
    return expireyLst
示例#21
0

# 1: Target Delta
targetDelta = st.number_input("What is your target portfolio delta?", 1)

# 2: Reduce/Increase/Neutralize exposure
reqDelta = (targetDelta * 100) - portfolioBWD
exposString = "No action required"
if (reqDelta < 0):
    exposString = "Reduce Exposure; Buy Puts of delta:" + str(reqDelta)
if (reqDelta > 0):
    exposString = "Add Exposure; Buy Calls of delta:" + str(reqDelta)

# 3: Expiry dates
# options import to find all expiry dates
benchMarkExpDate = options.get_expiration_dates(benchmark)
#stockExpirationDict = {}
st.write("Select hedge dates: ")
expDates = options.get_expiration_dates(benchmark)
#bestExpDates = find_closed_exp_dates(int(hedgeDay), int(hedgeMonth), int(hedgeYear), expDates, 3)
currentStr = "Select hedge date: "
#actualHedgeDate = st.radio(currentStr, bestExpDates)
actualHedgeDate = st.radio(currentStr, expDates)

# 4: correct option type
for stock in list:
    if (reqDelta < 0):
        optionType = 'puts'
    elif (reqDelta > 0):
        optionType = 'calls'
    else:
示例#22
0
import pandas
#expiration_dates = ops.get_expiration_dates("aapl")
#print(expiration_dates)
#index(['Contract Name', 'Last Trade Date', 'Strike', 'Last Price', 'Bid',
#       'Ask', 'Change', '% Change', 'Volume', 'Open Interest',
#       'Implied Volatility'],
#      dtype='object')

#stocks =  ["sq", "amd", "dis", "v"]
stocks = ["aapl", "nflx", "nvda", "tsla", "sq", "intc", "arkk", "tsm", "v"]
for s in stocks:
    period = 2
    p = si.get_live_price(s)
    print ("Stock %s, price = %.2f"%(s,p))
    expire_dates = ops.get_expiration_dates(s)
    for date in expire_dates:
        
        period -= 1
        if period < 0:
            break
        premium = int (p/100) + 0.5 
        
        options = ops.get_options_chain(s, date)
        start = p*1.05
        end = p*1.3
        print ("Checking Call option for %s premium %f for range %0.1f - %0.1f"%(date, premium, start,end ))
        
        calls = options["calls"]
        selected = calls.loc[(calls['Last Price']> premium ) & (calls['Strike']> start) & (calls['Strike']< end)  ]
        for ind in selected.index:
示例#23
0
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import robin_stocks as rh
import json
import userFunctions as uf
import rhorders as rho
from yahoo_fin import options
from yahoo_fin import stock_info as si

spy_tickers = si.tickers_sp500()
spy_tickers.append('SPY')
spy_tickers.append('TLT')
print(spy_tickers)
# scrape the options data for each Dow ticker
spy_data = {}
for ticker in spy_tickers:
    ticker_dates = options.get_expiration_dates(ticker)
    info = {}
    for date in ticker_dates:
        info[date] = options.get_options_chain(ticker)
        pd.DataFrame.to_csv('{}{}.csv'.format(ticker, date))
示例#24
0
def GetDates(ticker):
    exp_dates = options.get_expiration_dates(ticker)
    return pd.DataFrame(exp_dates)
示例#25
0
from yahoo_fin import options
import pandas as pd
import sys

if __name__ == '__main__':
    STOCK = sys.argv[1]
    with pd.ExcelWriter(STOCK + ".xlsx") as writer:
        for date in options.get_expiration_dates(STOCK):
            options_at_expiry = options.get_options_chain(STOCK, date)
            options_at_expiry["calls"].to_excel(writer,
                                                sheet_name=date + " calls")
            options_at_expiry["puts"].to_excel(writer,
                                               sheet_name=date + " puts")
示例#26
0
def extract_save_option_data(ticker):
    """
	Imports and saves from the yahoo finance database a company's option data. 
	The option data is split per type (call or put), expiration date, and day.
	It does:
		1. Checks for nested directories:
			<ticker>\options_data_<ticker>\<expiration_date>_<ticker>_<options>
			Creates it if non-existent. 
		2. Checks in the folder for a file named:
			<expiration_date>_<ticker>_<calls/puts>_as-at_<date_extract> 
			If so: merges the existing and newly extracted data.
		3. Saves the data (merged when applicable) in the folder under the company's 
		ticker.
	--------
	:param <ticker>: String ; ticker of a company traded on the financial markets
	"""
    extract_dates = options.get_expiration_dates(ticker)
    today = datetime.today().strftime("%Y-%m-%d")

    for expiration_date in extract_dates:
        format_date = arrow.get(expiration_date,
                                'MMMM D, YYYY').format('YYYY-MM-DD')
        extract_date = arrow.get(expiration_date,
                                 'MMMM D, YYYY').format('MM/DD/YYYY')

        try:
            extract = options.get_options_chain(ticker, extract_date)
            path = ticker + "\\options_data_" + ticker + "\\" + format_date + "_" + ticker + "_options"
            option_types = ["calls", "puts"]

            for option in option_types:
                extract_chain = extract[option]
                extract_chain = extract_chain.to_dict(orient="index")
                data_file_name = format_date + "_" + ticker + "_" + option + "_as-at_" + today

                # Step 1
                if not os.path.exists(path): os.makedirs(path)

                # Step 2
                if os.path.isfile(os.path.join(path, data_file_name)) == True:
                    try:
                        with open(os.path.join(path, data_file_name),
                                  'r') as file:
                            existing_data_in_file = json.load(file)
                            for item in existing_data_in_file:
                                extract_chain[item] = existing_data_in_file[
                                    item]

                    except Exception as e:
                        print(f"{ticker}: {e}")

                #Step 3
                with open(os.path.join(path, data_file_name), 'w') as f:
                    json.dump(extract_chain, f)
                    print(
                        f"{ticker}: {format_date} {option} options data retrieved successfully!\n"
                    )

        except Exception as e:
            print(
                f"{ticker}: {format_date} options data could not be retrieved.\n"
            )