Beispiel #1
0
def update_option_plot(ticker: str, dates: list):
    ticker = ticker.upper()
    price = stock_info.get_live_price(ticker)
    if dates:
        dfs = []
        for d in dates:
            df = options.get_calls(ticker, d)
            df['Expiry Date'] = d
            dfs.append(df)
        df = pd.concat(dfs)
    else:
        df = options.get_calls(ticker)
        df['Expiry Date'] = 'This Friday'

    fig = px.scatter(df,
                     x="Strike",
                     y="Last Price",
                     title=ticker,
                     size='Open Interest',
                     color='Expiry Date',
                     hover_data=['Open Interest', 'Implied Volatility'
                                 ]).update_traces(mode='lines+markers',
                                                  marker_line_width=2)

    fig.add_vline(price,
                  line_dash='dash',
                  line_color='green',
                  annotation_text=f'Current Stock Price: ${round(price, 2)}')
    fig.update_layout(plot_bgcolor=colors['background'],
                      paper_bgcolor=colors['background'],
                      font_color=colors['text'])
    return fig
Beispiel #2
0
def callPercentChange(ticker, strike):
    callChart = options.get_calls(ticker)
    csv = callChart.to_csv(ticker + '.csv')
    tickerDf = pd.read_csv(ticker + '.csv')
    oneRowDataframe = tickerDf.loc[tickerDf['Strike'] == strike]
    percentChange = oneRowDataframe.iloc[0]['% Change']
    return percentChange
Beispiel #3
0
def calculateStopLoss(ticker, strike, optionType):
    if optionType == 'Call' or optionType == 'call':
        callChart = options.get_calls(ticker)
        cdf = pd.DataFrame(callChart)
        oneRowDataframe = cdf.loc[cdf['Strike'] == strike]
        ask = oneRowDataframe.iloc[0]['Ask']
        bid = oneRowDataframe.iloc[0]['Bid']
        currPrice = oneRowDataframe.iloc[0]['Last Price']
        limitPriceUpper = (currPrice - (currPrice * .2)) - (ask - bid)
        limitPriceLower = (currPrice - (currPrice * .15)) - (ask - bid)
        if limitPriceLower < 0 or limitPriceUpper < 0:
            print("No need to set stop loss! This option premium is too low for a stop loss!")
        elif limitPriceUpper != limitPriceLower:
            print("Set Stop Loss Between: $", limitPriceUpper, "and $", limitPriceLower)




    if optionType == 'Put' or optionType == 'Put':
        putChart = options.get_puts(ticker)
        pdf = pd.DataFrame(putChart)
        oneRowDataframe = pdf.loc[pdf['Strike'] == strike]
        ask = oneRowDataframe.iloc[0]['Ask']
        bid = oneRowDataframe.iloc[0]['Bid']
        currPrice = oneRowDataframe.iloc[0]['Last Price']
        limitPriceUpper = (currPrice - (currPrice * .2)) - (ask - bid)
        limitPriceLower = (currPrice - (currPrice * .15)) - (ask - bid)
        if limitPriceLower < 0 or limitPriceUpper < 0:
            print("No need to set stop loss! This option premium is too low for a stop loss!")
        elif limitPriceUpper != limitPriceLower:
            print("Set Stop Loss Between: $", limitPriceUpper, "and $", limitPriceLower)
Beispiel #4
0
def callVolatility(ticker, strike):
    callChart = options.get_calls(ticker)
    csv = callChart.to_csv(ticker + '.csv')
    tickerDf = pd.read_csv(ticker + '.csv')
    oneRowDataframe = tickerDf.loc[tickerDf['Strike'] == strike]
    volatility = oneRowDataframe.iloc[0]['Implied Volatility']
    return volatility
Beispiel #5
0
def optimalDayTradeCall(ticker, date, type):
    callChart = options.get_calls(ticker, date)
    csv = callChart.to_csv(ticker + date + '.csv')
    tickerDf = pd.read_csv(ticker + date + '.csv')
    strikeList = tickerDf['Strike'].to_list()
    volumeList = tickerDf['Volume'].to_list()
    for i in range(len(volumeList)):
        if volumeList[i] == '-':
            volumeList[i] = int('0')
    #Volume Dictionary has keys as strike prices and values as volume
    volumeDictionary = {}
    keys = strikeList
    x = 0
    for i in keys:
        volumeDictionary[i] = int(volumeList[x])
        x += 1


    gammaDictionary = {}
    gammalist = []
    y = 0
    for i in strikeList:
        gammalist.append(calculateGreek(ticker, date, type, i, 'gamma'))
    for i in keys:
        gammaDictionary[i] = gammalist[y]
        y += 1
    y = 0

    #print(gammaDictionary)

    deltaDictionary = {}
    deltalist = []
    for i in strikeList:
        deltalist.append(calculateGreek(ticker, date, type, i, 'delta'))
    for i in keys:
        gammaDictionary[i] = deltalist[y]
        y += 1
    y = 0

    #print(gammaDictionary)

    thetadictionary = {}
    thetalist = []
    for i in strikeList:
        thetalist.append(calculateGreek(ticker, date, type, i, 'theta'))
    for i in keys:
        thetadictionary[i] = thetalist[y]
        y += 1
    y = 0

    #print(thetadictionary)

    gammaOrderedDict = {k: v for k, v in sorted(gammaDictionary.items(), key=lambda item: item[1])}
    volumeOrderedDict = {k: v for k, v in sorted(volumeDictionary.items(), key=lambda item: item[1])}
    deltaOrderedDict = {k: v for k, v in sorted(deltaDictionary.items(), key=lambda item: item[1])}

    thetaOrderedDict = {k: v for k, v in sorted(thetadictionary.items(), key=lambda item: item[1])}
Beispiel #6
0
    def update_options_list(self, option_type, strike, date):
        empty = {
            'Last Trade Date': '',
            'Strike': '',
            'Last Price': '',
            'Bid': '',
            'Ask': '',
            'Change': '',
            '% Change': '',
            'Volume': '',
            'Open Interest': '',
            'Implied Volatility': ''
        }
        contract_name = option_naming(self.ticker, strike, date, option_type)
        orig_date = date
        if contract_name not in self.observed_options:
            #breakdown date string
            """
            month_int = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November','December']
            month_today = month_int.index(date[0:date.index(' ')])+1
            date = date[date.index(' ')+1:]
            day_today = int(date[0:date.index(',')])
            year_today = int(date[-4:])
            strike_date_datetime = datetime.date(year_today, month_today, day_today)
            tod = datetime.date(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day)
            years_to_maturity = (strike_date_datetime-tod).days/365
            """
            years_to_maturity = years_to_maturity_calc(date)
            #get implied volatility
            if option_type.lower() == 'call':
                df = options.get_calls(self.ticker, orig_date)
            else:
                df = options.get_puts(self.ticker, orig_date)
            iv = float(df.loc[df['Strike'] == strike]['Implied Volatility'].
                       to_list()[0][0:-1].replace(',', '')) / 100

            #calculate greeks
            grks = option_greeks(self.prices_today[-1], strike,
                                 years_to_maturity, iv,
                                 self.risk_free_rate)[option_type.lower()]

            #calculate prices
            price = round(
                option_price(self.prices_today[-1], strike, years_to_maturity,
                             iv, self.risk_free_rate)[option_type.lower()], 2)

            opt = {
                'Expir Date': orig_date,
                'Strike Price': '${}'.format(strike)
            }

            opt['Value'] = '${}'.format(price)
            opt['Type'] = option_type
            opt['Implied Vol'] = '{}%'.format(np.round(iv * 100, 4))
            opt.update(grks)
            self.observed_options[contract_name] = opt
        return self.observed_options
Beispiel #7
0
def find_spreads(ticker, date, spread_type, rr=None, pop=None):
    try:
        curr_price = math.floor(si.get_live_price(ticker))
        if spread_type == 'cs':
            data = []
            puts = options.get_puts(ticker, date)
            puts_filtered = puts[puts['Strike'] <= curr_price]
            for i in range(0, len(puts_filtered) - 1):
                for j in range(i + 1, len(puts_filtered)):
                    calculate(spread_type, data, puts_filtered.iloc[i],
                              puts_filtered.iloc[j])
            df = pd.DataFrame(data,
                              columns=[
                                  'Strike 1\n(LONG)', 'Strike 2\n(SHORT)',
                                  'S1 Spread\nDiff', 'S2 Spread\nDiff',
                                  'Net\nCredit', 'Max\nLoss', 'Max\nGain',
                                  'Risk/Reward\nRatio', 'PoP\n(%)'
                              ])
            pd.set_option('display.max_rows', df.shape[0] + 1)
            if rr != None:
                df = df.loc[(df['Risk/Reward\nRatio'] >= float(rr))]
            if pop != None:
                df = df.loc[(df['PoP\n(%)'] >= float(pop))]
            # if rr == None and pop == None:
            #     df = df.loc[(df['Risk/Reward Ratio'] >= .25) & (df['PoP (%)'] <= 99.99)]
            return 'No good credit spreads found. The optional filters (R/R & PoP) may be too strict' if df.empty else df  # .sort_values(by='Risk/Reward', ascending=False)
        elif spread_type == 'ds':
            data = []
            calls = options.get_calls(ticker, date)
            calls_filtered = calls[calls['Strike'] >= curr_price]
            for i in range(0, len(calls_filtered) - 1):
                for j in range(i + 1, len(calls_filtered)):
                    calculate(spread_type, data, calls_filtered.iloc[i],
                              calls_filtered.iloc[j])
            df = pd.DataFrame(data,
                              columns=[
                                  'Strike 1\n(LONG)', 'Strike 2\n(SHORT)',
                                  'S1 Spread\nDiff', 'S2 Spread\nDiff',
                                  'Net\nDebit', 'Max\nLoss', 'Max\nGain',
                                  'Risk/Reward\nRatio', 'PoP\n(%)'
                              ])
            pd.set_option('display.max_rows', df.shape[0] + 1)
            if rr != None:
                df = df.loc[(df['Risk/Reward\nRatio'] >= float(rr))]
            if pop != None:
                df = df.loc[(df['PoP\n(%)'] >= float(pop))]
            # if rr == None and pop == None:
            #     df = df.loc[(df['Risk/Reward Ratio'] >= 2) & (df['PoP (%)'] >= 20)]
            return 'No good debit spreads found. The optional filters (R/R & PoP) may be too strict' if df.empty else df  # .sort_values(by='Risk/Reward', ascending=False)
        else:
            return 'Not a valid spread type'
    except AssertionError:
        return 'Not a valid ticker symbol'
    except ValueError:
        return 'Not a valid contract expiration date'
def calls_chain(ticka):
    calls = pd.DataFrame()
    stock_expiry_cache[ticka] = friday()
    while (calls.empty):
        try:
            calls = opt.get_calls(ticka, stock_expiry_cache[ticka])
        except:
            stock_expiry_cache[ticka] = stock_expiry_cache[ticka] + \
                dt.timedelta(days=7)
    calls['profit'] = calls['Last Price'] / calls['Strike']
    return calls
Beispiel #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
Beispiel #10
0
def get_chain(ticker, date=None, c_p='Call'):
    '''
	Gets option chain from Yahoo Finance API
	Inputs:
		ticker: (str) Stock or ETF ticker symbol
		date: (str) Indicates maturity date for option (e.g: "2019-12-06")
		c_p: (str) Indicates call or put option
	Returns:
		Pandas DataFrame of option chain
	'''
    cols = {'Implied Volatility': 'IV'}
    if c_p == 'Call':
        df = options.get_calls(ticker, date).rename(columns=cols)
        return df.set_index("Strike")
    if c_p == 'Put':
        df = options.get_puts(ticker, date).rename(columns=cols)
        return df.set_index("Strike")
Beispiel #11
0
def find_em(ticker, exp_date):
    sd = .6827
    curr_price = round(si.get_live_price(ticker), 2)
    low = curr_price - (curr_price * (1 - sd))
    high = curr_price + (curr_price * (1 - sd))
    calls = options.get_calls(ticker, exp_date)
    calls = calls.loc[(calls['Strike'] >= low) & (calls['Strike'] <= high)]
    new_calls = calls['Implied Volatility'].str.replace(r'%',
                                                        r'').astype('float')
    puts = options.get_puts(ticker, exp_date)
    puts = puts.loc[(puts['Strike'] >= low) & (puts['Strike'] <= high)]
    new_puts = puts['Implied Volatility'].str.replace(r'%',
                                                      r'').astype('float')
    volatility = round((new_calls.mean() + new_puts.mean()) / 2, 2)
    d1 = datetime.today()
    d2 = datetime.strptime(exp_date, '%m/%d/%y')
    days_left = abs(d1 - d2).days + 1
    em = round(
        si.get_live_price(ticker) * (volatility / 100) *
        math.sqrt(days_left / 365), 2)
    return 'Volatility: {}, Expected movement: -/+{}'.format(volatility, em)
Beispiel #12
0
# 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 *
                       3)) + (random.randrange(0, 51, 50) / 100)
    try:
        option_chain = options.get_calls(random_ticker, date=random_date)
    except:
        pass
else:
    #random OTM put strike price
    random_strike_price = round(random.uniform(
        0, current_price)) + (random.randrange(0, 51, 50) / 100)
    try:
        option_chain = options.get_puts(random_ticker, date=random_date)
    except:
        pass
# make number a multiple of 5 if it's not
# print(str(random.randrange(0,round(si.get_live_price(random_ticker)/3)+1,1) + random.randrange(0, 96, 5)/10))

print("Ticker: {0}\n{1}: ${2} {3}, literally can't go t**s up".format(
    random_ticker, random_date, str(round(random_strike_price, 2)),
async def on_message(message):
    print(message.content)
    if message.content.find("!") != -1:
        content = message.content.strip('!').lower().split()
        print(content)
        print(content[0])

        if content[0] == "day":
            if content[1] == "gain":
                await message.channel.send(
                    si.get_day_gainers().head(10).iloc[:, :3])
                await message.channel.send(
                    "-------------------------------------------")
                await message.channel.send(
                    si.get_day_gainers().head(10).iloc[:, 4:7])
            elif content[1] == "lose":
                await message.channel.send(
                    si.get_day_losers().head(10).iloc[:, :3])
                await message.channel.send(
                    "-------------------------------------------")
                await message.channel.send(
                    si.get_day_losers().head(10).iloc[:, 4:7])
            elif content[1] == "active":
                await message.channel.send(
                    si.get_day_most_active().head(10).iloc[:, :3])
                await message.channel.send(
                    "-------------------------------------------")
                await message.channel.send(
                    si.get_day_most_active().head(10).iloc[:, 4:7])

        elif content[0] == "crypto":
            await message.channel.send(si.get_top_crypto().head(10).iloc[:, :3]
                                       )
            await message.channel.send(
                "-------------------------------------------")
            await message.channel.send(si.get_top_crypto().head(10).iloc[:,
                                                                         4:5])

        elif content[0] == "help":
            embedVar = discord.Embed(title="List of functioning commands",
                                     description="",
                                     colour=0x00ff00)
            embedVar.add_field(name="\u200b",
                               value="!tsla\n!day gain\n!day loss",
                               inline=True)
            embedVar.add_field(
                name="\u200b",
                value="!calls tlsa 03/19/2021\n!puts tlsa 03/19/2021",
                inline=True)
            await message.channel.send(embed=embedVar)

        elif content[0] == "calls":
            await message.channel.send(
                op.get_calls(content[1], content[2]).iloc[:, 2:8])

        elif content[0] == "puts":
            await message.channel.send(
                op.get_puts(content[1], content[2]).iloc[:, 2:8])

        else:
            temp = si.get_quote_table(content[0])
            change = round(temp["Quote Price"] - temp["Previous Close"], 2)
            percentage = round(change / temp["Previous Close"] * 100, 2)

            displayQuote = str(round(temp["Quote Price"], 2))
            displayChange = str(change)
            displayPercentage = str(percentage)
            displayTicker = content[0].upper()
            displayClose = str(round(temp["Previous Close"], 2))

            dayRange = temp["Day's Range"].replace('-', '').split()

            dayLow = dayRange[0]
            dayHigh = dayRange[1]

            open = temp["Open"]
            close = temp["Previous Close"]

            volume = str(round(temp["Volume"] / 1000000, 2))
            volume = volume + "M"

            avgVolume = str(round(temp["Avg. Volume"] / 1000000, 2))
            avgVolume = avgVolume + "M"

            bid = temp["Bid"]
            ask = temp["Ask"]

            if change >= 0:
                rgb = 0x00ff00
                displayChange = "+" + displayChange
                displayPercentage = "+" + displayPercentage
            else:
                rgb = 0xff0000

            embedVar = discord.Embed(
                title=
                f"${displayTicker}\n${displayQuote} {displayChange} ({displayPercentage}%)",
                description="",
                colour=rgb)
            embedVar.add_field(
                name="\u200b",
                value=
                f"High: {dayHigh}\nLow: {dayLow}\n\nAsk: {ask}\nBid: {bid}",
                inline=True)
            embedVar.add_field(name="\u200b",
                               value=f"Open: {open}\nPrev.: {close}",
                               inline=True)
            embedVar.add_field(
                name="\u200b",
                value=f"Volume: {volume}\nAvg. Vol.: {avgVolume}",
                inline=True)

            await message.channel.send(embed=embedVar)
Beispiel #14
0
stock_corr_10d_ann = stock_corr_10d.multiply(sqrt(252))*100
stock_corr_5d = stock_returns.rolling(5).std()
stock_corr_5d_ann = stock_corr_5d.multiply(sqrt(255))*100

##########################################################################################

# WEC X=$95, C=#0.35, Exp = 10/18
X = 95
exp_date = datetime(2019, 10, 18)
days_to_exp = (exp_date - today).days
purchase_date = datetime(2019, 6, 20)
purchase_days_to_exp = (exp_date-purchase_date).days
cost = 0.35
S_purchase = stock[purchase_date]

calls = options.get_calls(ticker, exp_date)
V_market = pd.to_numeric(calls.loc[calls['Strike']==X, 'Last Price'].iloc[0])
IV_exp_yahoo = pd.to_numeric(calls.loc[calls['Strike']==X, 'Implied Volatility'].iloc[0].rstrip('%'))/100

##Implied Volatility - CALL
#def implied_vol_call(S,X,T,r,c):
#    from scipy import log, exp, sqrt, stats
#    for i in range(20000):
#        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.02:
#            return i,sigma,diff
##implied_vol_call(40,40,0.5,.05,3.3)
#implied_vol_call(90.42, 95, days_to_exp/365, 0, .96)
Beispiel #15
0
def Statement():
    page_bg_img = '''
    <style>
    body {
    background-image: url("https://images.pexels.com/photos/2748757/pexels-photo-2748757.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000");
    background-size: cover;
    }
    </style>
    '''
    st.markdown(page_bg_img, unsafe_allow_html=True)
    symbols = 'https://raw.githubusercontent.com/Moly-malibu/Stocks/main/bxo_lmmS1.csv'
    df = pd.read_csv(symbols)
    ticker = st.sidebar.selectbox('Stocks by Company', (df['Symbol']))
    tickerData = YahooFinancials(ticker)

    def get_symbol(symbol):
        url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(
            symbol)
        result = requests.get(url).json()
        for x in result['ResultSet']['Result']:
            if x['symbol'] == symbol:
                return x['name']

    company_name = get_symbol(ticker.upper())
    st.write("""# Analysis of """, company_name)
    company = yf.Ticker(ticker)
    # st.write(company.info)
    company_general = st.sidebar.checkbox("Financial Ratio")
    if company_general:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Financial Ratios</h1>",
            unsafe_allow_html=True)
        st.write('***Payout Ratio:*** ', company.info["payoutRatio"])
        st.write('***Trailing Annual Dividend Yield:*** ',
                 company.info["trailingAnnualDividendYield"])
        st.write('***Dividend Rate:*** ', company.info["dividendRate"])
        st.write('***Profit Margins: ***', company.info["profitMargins"])
        st.write('***Peg Ratio: ***', company.info["pegRatio"])
        yahoo_financials = YahooFinancials(ticker)
        marketcap = yahoo_financials.get_market_cap()
        price_to_sales = yahoo_financials.get_current_price()
        dividend_yield = yahoo_financials.get_dividend_yield()
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        st.write("""**Dividends**""", company.dividends)
        income = si.get_income_statement(ticker)
        transpose = income.transpose()
        interest_coverage1 = transpose['operatingIncome']
        interest_coverage2 = transpose['interestExpense']
        st.write(
            '***Interest Coverage:*** Operating Income / interest Expenses',
            interest_coverage1 / interest_coverage2)
        gross_profit_margin1 = transpose['totalRevenue']
        gross_profit_margin2 = transpose['costOfRevenue']
        st.write(
            '***Gross Profit Margin:*** Total Revenue / Gross Profit Margin',
            (gross_profit_margin1 - gross_profit_margin2) /
            gross_profit_margin1)
        balance = si.get_balance_sheet(ticker)
        transpose = balance.transpose()
        current_ratio1 = transpose['totalCurrentAssets']
        current_ratio2 = transpose['totalCurrentLiabilities']
        debt_to_assets1 = transpose['otherCurrentAssets']
        debt_to_assets2 = transpose['totalAssets']
        st.write('***Debit Assets:*** Total Debit / Total Assets',
                 (debt_to_assets1 / debt_to_assets2))
        debt_to_equity1 = transpose['otherCurrentAssets']
        debt_to_equity2 = transpose['totalStockholderEquity']
        st.write(
            '***Debit to Equity:*** Total Debit / Total Stock Holders Equity',
            (debt_to_equity1 / debt_to_equity2))
        ROE1 = transpose_income['netIncome']
        ROE2 = transpose_balance['totalStockholderEquity']
        st.write(
            '***Return On Equity ROE:*** Net Income / (Total Stock Holder Equity + Total Stock Holder Equity)/2',
            (ROE1 / ((ROE2 + ROE2) / 2)))
        ROA1 = transpose_income['netIncome']
        ROA2 = transpose_balance['totalAssets']
        st.write('***Return On Assets:*** Net Income / Total Assets',
                 (ROA1 / ROA2))

    company_simulation = st.sidebar.checkbox("Monte Carlo Simulation")
    if company_simulation:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Monte Carlo Simulation Price</h1>",
            unsafe_allow_html=True)
        st.write(
            """Monte Carlo Simulation project future price for the stocks. """)
        yahoo_financials = YahooFinancials(ticker)
        price = yahoo_financials.get_current_price()
        st.write('***Current Price:***', price)
        marketcap = yahoo_financials.get_market_cap()
        st.write('***Market Capital***', marketcap)
        income_balance = si.get_income_statement(ticker)
        transpose_income = income_balance.transpose()
        revenue = transpose_income['totalRevenue']
        st.write('***Price to sales:*** (Market Capital / Revenue',
                 marketcap / revenue)
        price_to_earnings = transpose_income['netIncome']
        st.write('***Price to Earnings:*** (Market Capital/ Net Income',
                 marketcap / price_to_earnings)
        balance_income = si.get_balance_sheet(ticker)
        transpose_balance = balance_income.transpose()
        price_to_book = transpose_balance['totalStockholderEquity']
        st.write('***Price to book:*** (marketcap/Total Stock Holders Equity',
                 marketcap / price_to_book)
        start = st.date_input("Please enter date begin Analysis: ")
        price = yf.download(ticker, start=start, end=None)['Close']
        returns = price.pct_change()
        last_price = price[-1]
        num_simulations = 1000
        num_days = 252
        num_simulations_df = pd.DataFrame()
        for x in range(num_simulations):
            count = 0
            daily_vol = returns.std()
            price_series = []
            price = last_price * (1 + np.random.normal(0, daily_vol))
            price_series.append(price)
            for y in range(num_days):
                if count == 251:
                    break
                price = price_series[count] * (1 +
                                               np.random.normal(0, daily_vol))
                price_series.append(price)
                count += 1
            num_simulations_df[x] = price_series
        fig = plt.figure()
        plt.title('Monte Carlo Simulation')
        plt.plot(num_simulations_df)
        plt.axhline(y=last_price, color='r', linestyle='-')
        plt.xlabel('Day')
        plt.ylabel('Price')
        st.set_option('deprecation.showPyplotGlobalUse', False)
        st.pyplot()
        st.write('Price Series Predict: ', num_simulations_df)
    # company_general = st.sidebar.checkbox("Quick_Ratio")
    # if company_general:
    #     st.subheader("""**Quick Ratio**""")
    #     balance=si.get_balance_sheet(ticker)
    #     transpose=balance.transpose()
    #     quick_ratio1 = transpose['otherCurrentAssets']
    #     quick_ratio2 = transpose['inventory']
    #     quick_ratio3 = transpose['otherCurrentLiab']
    #     quick_ratio = ((quick_ratio1-quick_ratio2)/quick_ratio3)
    #     if not quick_ratio2:
    #         st.write("No data available")
    #     else:
    #         st.write('(***Quick Ratio:*** CurrentAssets - Inventory)/Current Liabilities)', (quick_ratio1-quick_ratio2)/quick_ratio3)
    company_hist = st.sidebar.checkbox("Cash Flow")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Cash Flow</h1>",
            unsafe_allow_html=True)
        display_cash = si.get_cash_flow(ticker)
        if display_cash.empty == True:
            st.write("No data available")
        else:
            st.write(display_cash)
    company_hist = st.sidebar.checkbox("Income Statement")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Income Statement</h1>",
            unsafe_allow_html=True)
        display_income_stat = si.get_income_statement(ticker)
        if display_income_stat.empty == True:
            st.write("No data available")
        else:
            st.write(display_income_stat)
    company_hist = st.sidebar.checkbox("Balance Sheet")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Balance Sheet</h1>",
            unsafe_allow_html=True)
        display_balance = si.get_balance_sheet(ticker)
        if display_balance.empty == True:
            st.write("No data available")
        else:
            st.write(display_balance)
    company_hist = st.sidebar.checkbox("Quote Table")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Quote Table</h1>",
            unsafe_allow_html=True)
        display_table = si.get_quote_table(ticker, dict_result=False)
        if display_table.empty == True:
            st.write("No data available")
        else:
            st.write(display_table)
        quote_table = si.get_quote_table(ticker)
        t = quote_table["Forward Dividend & Yield"]
        st.write('Forward Dividend & Yield:', t)
        display_capital = si.get_quote_table(ticker)["Market Cap"]
        st.write('Market Capital', display_capital)
    company_hist = st.sidebar.checkbox("Call Option")
    if company_hist:
        st.markdown(
            "<h1 style='text-align: center; color: #002966;'>Call Option</h1>",
            unsafe_allow_html=True)
        c = ops.get_calls(ticker)
        transpose = c.transpose()
        st.write(transpose)
Beispiel #16
0
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')
print(chain[chain['Strike'] <= 150]
      )  # Get all rows where strike price is less than 150
print('\n')

chain = options.get_puts(stock, 'August 20, 2021')
#print(chain)
print('PUT Options: Strike <=150 \n')
print(chain[chain['Strike'] <= 150]
      )  # Get all rows where strike price is less than 150
print('\n')
Beispiel #17
0
import yahoo_fin.options as ops
import statistics

df = ops.get_calls("ual")
print(len(df["Implied Volatility"]), "calls")
print("Mean σ:",
      statistics.mean([float(i[:-1]) for i in df["Implied Volatility"]]) / 100)