Example #1
0
from matplotlib import pyplot as plt
import yfinance as yf
import pandas as pd

#matplotlib theme
plt.style.use("seaborn-dark")

#enter a valid stock ticker, code breaks when you request etf(s)
stock = yf.Ticker(input("enter stock ticker: "))

#You must choose one of the following
print("\n[1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max ]\n")

time = input("enter period: ")
priceHistory = stock.history(period=time)
stockName = stock.info['shortName']

#pandas DataFrame
df = priceHistory

#Visualize using matplotlib
plt.figure()
plt.plot(df['Close'])
plt.title(stockName + " Price history")
plt.xlabel("Time Frame: " + time)
plt.tight_layout()
plt.show()

#note, remember to exit graph window in order to re-run code. Happy Coding!
Example #2
0
def yfinancetut(tickersymbol):
    tickerdata = yf.Ticker(tickersymbol)
    tickerinfo = tickerdata.info
    stock = tickerinfo['shortName']
    return stock
Example #3
0
def yfPtoE(tickersymbol):
    tickerdata = yf.Ticker(tickersymbol)
    tickerinfo = tickerdata.info
    PricetoEarnings = tickerinfo['forwardPE']
    return PricetoEarnings
Example #4
0
#%%
from usingYahoo import fetchFromYahoo, get_train_test_dataset, create_dataset
import yfinance as yf
import matplotlib.pyplot as plt

print('\nNifty \n' , yf.Ticker("^NSEI").history(period='max')[::-1])
plt.plot(yf.Ticker("^NSEI").history(period='max')['Close'])
plt.title('NIFTY 50')
plt.show()

print('\nSensex \n' , yf.Ticker("^BSESN").history(period='max')[::-1])
plt.plot(yf.Ticker("^BSESN").history(period='max')['Close'])
plt.title('SENSEX')
plt.show()

#creating dataset 
df,info = fetchFromYahoo('BEPL.NS')
train_data, test_data = get_train_test_dataset(df)
xtrain, ytrain = create_dataset(train_data, timestep=100)
xtest, ytest = create_dataset(test_data, timestep=100)
# %%
xtrain = xtrain.reshape(xtrain.shape[0],xtrain.shape[1],1)
xtest = xtest.reshape(xtest.shape[0],xtest.shape[1],1)

# %%
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
model = Sequential()
model.add(LSTM(100,return_sequences=True, input_shape = (xtrain.shape[1],xtrain.shape[2])))
model.add(LSTM(100, return_sequences=True))
model.add(Dropout(0.3))
def check_presets(preset_dict: dict) -> str:
    """Checks option screener preset values

    Parameters
    ----------
    preset_dict: dict
        Defined presets from configparser
    Returns
    -------
    error: str
        String of all errors accumulated
    """
    float_list = [
        "min-iv",
        "max-iv",
        "min-oi",
        "max-oi",
        "min-strike",
        "max-strike",
        "min-volume",
        "max-volume",
        "min-voi",
        "max-voi",
        "min-diff",
        "max-diff",
        "min-ask-bid",
        "max-ask-bid",
        "min-exp",
        "max-exp",
        "min-price",
        "max-price",
        "min-price-20d",
        "max-price-20d",
        "min-volume-20d",
        "max-volume-20d",
        "min-iv-20d",
        "max-iv-20d",
        "min-delta-20d",
        "max-delta-20d",
        "min-gamma-20d",
        "max-gamma-20d",
        "min-theta-20d",
        "max-theta-20d",
        "min-vega-20d",
        "max-vega-20d",
        "min-rho-20d",
        "max-rho-20d",
        "min-price-100d",
        "max-price-100d",
        "min-volume-100d",
        "max-volume-100d",
        "min-iv-100d",
        "max-iv-100d",
        "min-delta-100d",
        "max-delta-100d",
        "min-gamma-100d",
        "max-gamma-100d",
        "min-theta-100d",
        "max-theta-100d",
        "min-vega-100d",
        "max-vega-100d",
        "min-rho-100d",
        "max-rho-100d",
        "min-sto",
        "max-sto",
        "min-yield",
        "max-yield",
        "min-myield",
        "max-myield",
        "min-delta",
        "max-delta",
        "min-gamma",
        "max-gamma",
        "min-theta",
        "max-theta",
        "min-vega",
        "max-vega",
        "min-cap",
        "max-cap",
    ]
    bool_list = [
        "active", "stock", "etf", "puts", "calls", "itm", "otm", "exclude"
    ]
    error = ""
    for key, value in preset_dict.items():
        if key in float_list:
            try:
                float(value)
                if value.startswith("."):
                    error += f"{key} : {value} needs to be formatted with leading 0\n"
            except Exception:
                error += f"{key} : {value}, should be float\n"

        elif key in bool_list:
            if value not in ["true", "false"]:
                error += f"{key} : {value},  Should be [true/false]\n"

        elif key == "tickers":
            for ticker in value.split(","):
                try:
                    if yf.Ticker(
                            eval(ticker)).info["regularMarketPrice"] is None:
                        error += f"{key} : {ticker} not found on yfinance"

                except NameError:
                    error += f"{key} : {value}, {ticker} failed"

        elif key == "limit":
            try:
                int(value)
            except Exception:
                error += f"{key} : {value} , should be integer\n"

        elif key == "order-by":
            accepted_orders = [
                "e_desc",
                "e_asc",
                "iv_desc",
                "iv_asc",
                "md_desc",
                "md_asc",
                "lp_desc",
                "lp_asc",
            ]
            if value not in accepted_orders:
                error += f"{key} : {value} not accepted ordering\n"

    return error
Example #6
0
def close():
    close_body = ""
    a_stocks_body_text = ""
    b_stocks_body_text = ""
    a_sum_day_list = []
    b_sum_day_list = []
    for stocks in my_stocks:
        header = ("Stock name: " + stocks.Name + ",  Ticker :" + stocks.Ticker)
        individual_stock_data = yf.Ticker(stocks.Ticker)
        individual_stock_data.history(period="2d")
        num_shares = stocks.Shares

    for stocks in a_stocks:
        header_a = ("Stock Name: " + stocks.Name + ", Ticker: " +
                    stocks.Ticker)
        num_shares = stocks.Shares
        individual_stock_data = yf.Ticker(stocks.Ticker)
        open_string_data_1_d = str(
            individual_stock_data.history(period="1d").Open[0])
        close_string_data_1_d = str(
            individual_stock_data.history(period="1d").Close[0])
        day_change_1d = (float(close_string_data_1_d) -
                         float(open_string_data_1_d))
        close_value_1d = float(num_shares) * float(close_string_data_1_d)
        open_value_1 = float(open_string_data_1_d) * float(num_shares)
        change_value_1 = (close_value_1d - open_value_1)
        change_percent_a = ((change_value_1 / open_value_1) * 100)
        a_sum_day = a_sum_day_list.append(change_value_1)
        a_stocks_body_text += """{} \n {} \n {} \n {} \n {} \n {} \n {} \n \n""".format(
            header_a, "Close: " + str(todays_date) + " " + "$" +
            str(close_string_data_1_d), "Shares :" + stocks.Shares,
            "Current Value : $" + ('%.2f' % close_value_1d),
            "Daily $ Price Change:  $" + ('%.2f' % day_change_1d),
            "Daily % Price Change: " + ('%.2f' % change_percent_a + " %"),
            "Daily Value Change: $" + ('%.2f' % change_value_1))

    for stocks in b_stocks:
        header_b = ("Stock Name: " + stocks.Name + ", Ticker: " +
                    stocks.Ticker)
        num_shares = stocks.Shares
        individual_stock_data = yf.Ticker(stocks.Ticker)
        open_string_data_2_d = str(
            individual_stock_data.history(period="3d").Open[-2])
        close_string_data_2_d = str(
            individual_stock_data.history(period="3d").Close[-1])
        day_change_2d = Decimal(
            float(close_string_data_2_d) - float(open_string_data_2_d))
        day_change_rounded = round(day_change_2d, 2)
        close_value_2d = float(num_shares) * float(close_string_data_2_d)
        open_value_2 = float(open_string_data_2_d) * float(num_shares)
        change_value_2 = (close_value_2d - open_value_2)
        change_percent = ((change_value_2 / open_value_2) * 100)
        b_sum_day = b_sum_day_list.append(change_value_2)
        b_stocks_body_text += """ \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n \n""".format(
            header_b, "Close: " + str(todays_date) + " " + "$" +
            str(close_string_data_2_d), "Shares :" + stocks.Shares,
            "Current Value: $" + ('%.2f' % close_value_2d),
            "Daily $ Price Change: $" + ('%.2f' % day_change_2d),
            "Daily % Price Change: " + ('%.2f' % change_percent + " %"),
            "Daily Value Change: $" + ('%.2f' % change_value_2))
    a_total = sum(a_sum_day_list)
    b_total = sum(b_sum_day_list)
    day_total = a_total + b_total
    total_text = "Day Totals: $ "
    close_body = str(a_stocks_body_text) + str(b_stocks_body_text) + str(
        total_text + ('%.2f' % day_total))

    email_to_send = ezgmail.send('Any_email.com', subject_text, close_body)
Example #7
0
    if column.text.strip() == dividendname:
        dividendIndex = i
        print(i, column.text.strip())
        break

if dividendIndex == -sys.maxsize:
    sys.exit('Table without Dividened column???')

tablerow = tablebody.find_elements_by_tag_name('tr')
print('Number of rows = ', len(tablerow))

for i, row in enumerate(tablerow):
    dataset = row.find_elements_by_tag_name('td')

    stock_symbol = dataset[0].text.strip()
    ticker = yf.Ticker(stock_symbol)
    today_price = ticker.history().tail(1)
    dividend_amount = float(dataset[dividendIndex - 1].text.strip())
    print(
        stock_symbol, today_price.columns[0], today_price['Close'],
        dividend_amount)  # dividend_amount / today_price['Close'] * 100, '%')

    if i == len(tablerow) - 1:
        driver.get(stockurl + dataset[0].text.strip())
        # today_price = driver.find_element_by_class_name('symbol-page-header__pricing-price')
        # print( 'Today price', today_price.text.strip())

#if driver.find_element_by_class_name("pagination__next"):
#    driver.find_element_by_class_name("pagination__next").click()

# driver.close()
Example #8
0
    plt.xlabel('Date')
    plt.ylabel('Price [$]')
    FFT = np.fft.fft(np.asarray(
        data.values.tolist()))  # Get the fast fourier transform
    plots = []
    for num in [3, 6, 9, 15]:
        fft = np.copy(FFT)
        fft[num:-num] = 0
        ifft = np.fft.ifft(fft)
        p = plt.plot(pd.to_datetime(
            np.linspace(
                pd.Timestamp(data.index.values[0]).value,
                pd.Timestamp(data.index.values[-1]).value, len(ifft))),
                     np.real(ifft),
                     linestyle='--',
                     label='Fourier transform with %d components' % num)
        plots.append(p)
    p = plt.plot(data.index, data.values, color='purple', ls='-', label='Real')
    plots.append(p)
    return plots


if __name__ == '__main__':
    import yfinance as yf
    SPCE = yf.Ticker('SPCE')
    hist = SPCE.history(period='max')
    plt.figure()
    plot_fourier(hist['Close'])
    plt.legend()
    plt.show()
Example #9
0
def get_yfinance_m(stock, period):
    features = ['Open', 'High', 'Low', 'Close', 'Volume']
    val = yf.Ticker(stock)
    val_historical = val.history(period=period, interval="1m")
    return val_historical[features]
Example #10
0
def evaluate(stocks):
    #read date and do basic processing
    date_cols = ['Zeit']
    df = pd.read_csv('./tmp/scraped_news.csv', parse_dates=date_cols)
    df['Datum'] = df['Zeit'].dt.date
    df['Stunde'] = df['Zeit'].dt.time
    #df['Schlagzeile'] = df['Schlagzeile'].astype("|S")
    df['Aktie'] = stocks[0]
    df = df.loc[(df['Leser'] != 'Werbung')
                & (df['Schlagzeile'].values != None)
                & (df['Zeit'].values != None)]
    df = df.reset_index(drop=True)
    df.to_excel('./tmp/scraped_and_cleaned_news.xlsx',
                index=False,
                sheet_name='data')

    #translate
    chunk_size = 5
    chs = []
    for i in chunker(df, chunk_size):
        chs.append(i)

    trl = []
    for i in range(len(chs)):
        trl.append(
            googletranslate_en(
                [str(j) for j in chs[i]['Schlagzeile'].tolist()[:]]))

    flatten = lambda t: [item for sublist in t for item in sublist]
    trls = flatten(trl)
    df['Schlagzeile EN'] = trls
    df = df.replace('in', 'xyz')

    #sentiment analysis
    # Instantiate the sentiment intensity analyzer
    vader = SentimentIntensityAnalyzer()

    # Set column names
    columns = ['Aktie', 'Datum', 'Stunde', 'Schlagzeile EN']

    # Convert the parsed_news list into a DataFrame called 'parsed_and_scored_news'
    parsed_and_scored_news = pd.DataFrame(df, columns=columns)
    parsed_and_scored_news = parsed_and_scored_news.reset_index(drop=True)

    # Iterate through the headlines and get the polarity scores using vader
    scores = parsed_and_scored_news['Schlagzeile EN'].apply(
        vader.polarity_scores).tolist()

    # Convert the 'scores' list of dicts into a DataFrame
    scores_df = pd.DataFrame(scores)

    # Join the DataFrames of the news and the list of dicts
    parsed_and_scored_news = parsed_and_scored_news.join(scores_df,
                                                         rsuffix='_right')

    # Convert the date column from string to datetime
    parsed_and_scored_news['Datum'] = pd.to_datetime(
        parsed_and_scored_news.Datum).dt.date

    #plots
    plot_vaderscores(parsed_and_scored_news, './tmp/fig_vaderscores.png')

    cnt_df = plot_countofnewsperday(parsed_and_scored_news,
                                    './tmp/fig_countofnewsperday.png')

    nvda = yf.Ticker("NVDA")
    hist = nvda.history(period="30d")
    cnt_df.index = pd.to_datetime(cnt_df.index)
    mask = (hist.index >= min(cnt_df.index))
    nvda_df = hist.loc[mask]
    plot_closeprice(nvda_df, './tmp/fig_closeprice.png')

    print('Evaluation successful!')
Example #11
0
def getBuiltInRankings():
    stock_list = StockInfo.objects.all()
    list_size = len(stock_list)

    # check validity of data
    stock = stock_list[0]
    ticker = yf.Ticker(f'{stock.ticker}.TW')
    his = ticker.history(period='1d', actions=False)
    # valid
    if datetime.today().date() == his.index[0]:
        rise = np.zeros(list_size)
        fall = np.zeros(list_size)
        volume = np.zeros(list_size)

        for i in range(list_size):
            stock = stock_list[i]
            ticker = yf.Ticker(f'{stock.ticker}.TW')
            his = ticker.history(period='1d', actions=False)
            if his.empty:
                continue
            # rise, fall, volume
            rise[i] = (his['Close'][0] - his['Open'][0]) / his['Open'][0]
            fall[i] = -rise[i]
            volume[i] = his['Volume'][0]

        # sort
        top_rise = rise.argsort()[-RANKING_SIZE:][::-1]
        top_fall = fall.argsort()[-RANKING_SIZE:][::-1]
        top_volume = volume.argsort()[-RANKING_SIZE:][::-1]

        # delete old records
        # consider deleting all of them? yes?
        if StockRecord.objects.all().exists:
            StockRecord.objects.all().delete()

        # store data into database
        # Model.objects.bulk_create([ Model(**{variable: value, ...}) for m in list ])
        StockRecord.objects.bulk_create([
            StockRecord(
                **{
                    'record_type': 'rise',
                    'stock_info': stock_list[int(top_rise[i])],
                    'ranking_number': i + 1,
                    'last_modified': his.index[0],
                    'remark': f'{round( rise[ int(top_rise[i]) ] * 100, 2 )}%'
                }) for i in range(RANKING_SIZE)
        ])
        StockRecord.objects.bulk_create([
            StockRecord(
                **{
                    'record_type': 'fall',
                    'stock_info': stock_list[int(top_fall[i])],
                    'ranking_number': i + 1,
                    'last_modified': his.index[0],
                    'remark': f'{round( fall[ int(top_fall[i]) ] * 100, 2 )}%'
                }) for i in range(RANKING_SIZE)
        ])
        StockRecord.objects.bulk_create([
            StockRecord(
                **{
                    'record_type': 'volume',
                    'stock_info': stock_list[int(top_volume[i])],
                    'ranking_number': i + 1,
                    'last_modified': his.index[0],
                    'remark': f'{volume[ int(top_volume[i]) ]}'
                }) for i in range(RANKING_SIZE)
        ])
Example #12
0
def ValuationStatement(currentprice, intrinsicprice, ValueComparison):
    if currentprice - intrinsicprice >= 0:
        statement = "Shares overvalued by {}".format(ValueComparison)
    elif currentprice - intrinsicprice <= 0:
        statement = "Shares undervalued by {}".format(ValueComparison)

    return statement


#loop the tickers specified and pulling with API from yFinance

for tickerIndex in ticker_list:
    try:
        ticker = tickerIndex  #str(input("ticker symbol: ")) #example: MSFT
        tkr = yf.Ticker(ticker)
        Bta = tkr.info['beta']
        curr_share_value = tkr.info['regularMarketPrice']
        numshares = tkr.info['sharesOutstanding']

        netincome = tkr.financials.loc['Net Income', :].tolist()
        byNI = netincome[0]

        bookvalue1 = tkr.balancesheet.loc[
            'Total Stockholder Equity', :].tolist()
        byBV = bookvalue1[0]
        pyBV = bookvalue1[1]

        divy = tkr.dividends.tolist()
        byDivtemp = divy.reverse()
        byDivtemp = divy[0:4]
Example #13
0
import yfinance as yf
import pandas as pd
from time import sleep
while True:
    tatasteel = yf.Ticker('TATASTEEL.NS')
    df = pd.DataFrame(tatasteel.history('1d', '1m'))
    df = df[['High', 'Low', 'Volume']][-7:]
    high = df[['High']].values
    low = df[['Low']].values
    flag = 0
def get_sector(ticker):
    try:
        return yf.Ticker(ticker).info["sector"]
    except (ValueError, IndexError):
        return "Other"
Example #15
0
def get_linearprediction(ticker_name, start_date, end_date, future_period):
    import datetime
    from datetime import timedelta, date
    #Download the data from Yfinance
    ticker = yf.Ticker(ticker_name)
    ticker_historical = ticker.history(start=start_date, end=end_date)
    ticker_historical  #Display the data

    name = ticker_name
    filename = "%s.csv" % name
    #Save data into a CSV file
    ticker_historical.to_csv(filename)

    #df.to_csv(filename)
    df = pd.read_csv(filename)

    df_days = df[['Date']]
    # print(df)

    # A variable for predicting 'n' days out into the future #'n=30' days

    # Get the Adjusted Close Price
    df = df[['Close']]

    #Create another column (the target ) shifted 'n' units up
    df['Prediction'] = df[['Close']].shift(-future_period)
    #print the new data set
    #print(df.tail())

    ### Create the independent data set (X)  #######
    # Convert the dataframe to a numpy array
    X = np.array(df.drop(['Prediction'], 1))

    #Remove the last '30' rows
    X = X[:-future_period]
    #print(X)

    ### Create the dependent data set (y)  #####
    # Convert the dataframe to a numpy array
    y = np.array(df['Prediction'])
    # Get all of the y values except the last '30' rows
    y = y[:-future_period]
    #print(y)

    # Split the data into 80% training and 20% testing
    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    # Create and train the Linear Regression  Model
    lr = LinearRegression()
    # Train the model
    lr.fit(x_train, y_train)

    # Testing Model: Score returns the coefficient of determination R^2 of the prediction.
    # The best possible score is 1.0
    lr_confidence = lr.score(x_test, y_test)
    #print("lr confidence: ", lr_confidence)

    # df['Linear Regression Accuracy'] = lr_confidence
    # Set x_forecast equal to the last 30 rows of the original data set from Adj. Close column
    x_forecast = np.array(df.drop(['Prediction'], 1))[-future_period:]
    #print(x_forecast)

    #Print linear regression model predictions for the next '30' days
    lr_prediction = lr.predict(x_forecast)
    #print(lr_prediction)

    df['Date'] = df_days
    df

    # A variable for predicting 'n' days out into the future

    start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()

    def daterange(date1, date2):
        for n in range(int((date2 - date1).days) + 1):
            yield date1 + timedelta(n)

    for lr in lr_prediction:
        end_date += timedelta(days=1)
        #print(end_date)
        weekdays = [5, 6]
        df = df.append({
            'Date': end_date,
            'Linear Regression Prediction': lr
        },
                       ignore_index=True)
    df = df[['Date', 'Close', 'Linear Regression Prediction']]
    return df
Example #16
0
import yfinance as yf
import pandas as pd
import numpy as np
import streamlit as st

st.write("""
# Simple Stock Price App
are the stock ***closing price*** and ***volume*** of Google
Shown

""")

tickerSymbol = 'GOOGL'
tickerData = yf.Ticker(tickerSymbol)
tickerDf = tickerData.history(period='id', start='2010-5-31', end='2020-5-31')

st.line_chart(tickerDf.Close)
st.line_chart(tickerDf.Volume)
Example #17
0
    "1.5", "B")
veirx_stock = Stock("Vanguard Equity-Income Fund Admiral Shares", "VEIRX",
                    "1.5", "B")
rds_a_stock = Stock("Royal Dutch Shell plc", "RDS-A", "1.5", "A")
ldlfx_stock = Stock("Lord Abbett Short Duration Income Fund Class F ", "LDLFX",
                    "1.5", "B")

my_stocks = [
    ba_stock, vug_stock, stx_stock, trrmx_stock, svaix_stock, veirx_stock,
    rds_a_stock, ldlfx_stock
]
a_stocks = [ba_stock, rds_a_stock, stx_stock, vug_stock]
b_stocks = [trrmx_stock, ldlfx_stock, svaix_stock, veirx_stock]
subject_text = """{} {}""".format("Stocks Closing Price:", todays_date)

individual_stock_data = yf.Ticker("VEIRX")
open_val = (individual_stock_data.history(period="3d").Open[-2] * 114.568)
close_val = (individual_stock_data.history(period="3d").Close[-1] * 114.568)
change_val = Decimal(close_val - open_val)


def close():
    close_body = ""
    a_stocks_body_text = ""
    b_stocks_body_text = ""
    a_sum_day_list = []
    b_sum_day_list = []
    for stocks in my_stocks:
        header = ("Stock name: " + stocks.Name + ",  Ticker :" + stocks.Ticker)
        individual_stock_data = yf.Ticker(stocks.Ticker)
        individual_stock_data.history(period="2d")
Example #18
0
def yf_downloader(symbols, **kwargs):  # pragma: no cover
    """Downloader that uses `yfinance`."""
    import yfinance as yf

    return {s: yf.Ticker(s).history(**kwargs) for s in symbols}
Example #19
0
def download_returns(ticker, period="max"):
    if isinstance(period, _pd.DatetimeIndex):
        p = {"start": period[0]}
    else:
        p = {"period": period}
    return _yf.Ticker(ticker).history(**p)['Close'].pct_change()
Example #20
0
def get_current_stock_value(ticker):
    stock = yf.Ticker(ticker)
    history = stock.history(period='2d', interval='1d')
    return history.iloc[-1]['Close']
Example #21
0
def get_roe(ticker, exchange, freq='yearly'):
    ''' Retrieves the balance sheet and financials from yfinance. Calculates the average shareholder equity and
    determines the Return on Equity '''

    def match_dates(frame1, frame2):
        """ Returns the intersection of dates between two input frames and the smallest date """
        dates_frame1 = frame1.index.strftime('%Y-%m-%d')
        print(dates_frame1)
        dates_array1 = pd.Index.ravel(dates_frame1, order='C')
        print(dates_array1)
        dates_frame2 = frame2.index.strftime('%Y-%m-%d')
        dates_array2 = pd.Index.ravel(dates_frame2, order='C')
        return_array = np.intersect1d(dates_array1, dates_array2)
        minimum = np.amin(return_array)
        return return_array, minimum 

    if (exchange == 'ASX'):
        ticker += '.AX'

    stock = yf.Ticker(ticker)

    if freq == 'yearly':
        netIncomeDf = stock.financials.loc['Net Income'].to_frame()
        netIncomeDf = netIncomeDf.iloc[::-1]
        shareholderEquityDf = stock.balance_sheet.loc['Total Stockholder Equity'].to_frame()
        shareholderEquityDf = shareholderEquityDf.iloc[::-1]
    else:
        netIncomeDf = stock.quarterly_financials.loc['Net Income'].to_frame()
        netIncomeDf = netIncomeDf.iloc[::-1]
        shareholderEquityDf = stock.quarterly_balance_sheet.loc['Total Stockholder Equity'].to_frame()
        shareholderEquityDf = shareholderEquityDf.iloc[::-1]
    
    averageShareHolderEquity = []
    returnOnEquity = []
    dates, minDate = match_dates(netIncomeDf, shareholderEquityDf)

    for index, _ in enumerate(dates):
        currDate = dates[index]
        prevDate = dates[index - 1]
        if currDate == minDate:
            # we cannot calculate the average for the first date
            averageShareHolderEquity.append(0)
            returnOnEquity.append(0)
            continue

        currNetIncome = netIncomeDf.loc[np.datetime64(currDate)]['Net Income']
        currSE = shareholderEquityDf.loc[np.datetime64(currDate)]['Total Stockholder Equity']
        prevSE = shareholderEquityDf.loc[np.datetime64(prevDate)]['Total Stockholder Equity']
        
        avgSE = (prevSE + currSE) / 2
        averageShareHolderEquity.append(avgSE)
        
        roe = currNetIncome / avgSE
        returnOnEquity.append(roe)
    
    # Create dataframe to be processed
    data = list(zip(averageShareHolderEquity, returnOnEquity))
    finalDf = pd.DataFrame(data, columns=['average_shareholder_equity', 'return_on_equity'], index=dates)
    
    roeDict = json.loads(finalDf.transpose().to_json())

    roeArray = []
    # front end requires the data to be in this format
    for date in roeDict.keys():
        roeArray.append({
            'entry': 'return_on_equity',
            'date': date,
            'value': roeDict.get(date).get('return_on_equity'),
        })
    
    return roeArray
Example #22
0
def get_stock_value_time(ticker):
    stock = yf.Ticker(ticker)
    history = stock.history(period='5d', interval='1d')
    # print(history.loc[:, ['Close']])
    return history.loc[:, ['Close']]
Example #23
0
# st.markdown('''
# # Stock Information
# ''')

#Sidebar panel
st.sidebar.subheader('Query Parameters')
start_date = st.sidebar.date_input("Start date", datetime.date(2020, 1, 1))
# end_date=st.sidebar.date_input("End date",datetime.date(2021,5,12))
end_date = st.sidebar.date_input("End date", datetime.date.today())

#Retriveing ticker data
ticker_list = ['CBRE', 'AAPL', 'GOOG', 'FB', 'MSFT', 'AMZN', 'PLTR', 'U']
tickerSymbol = st.sidebar.selectbox('Stock Ticker',
                                    ticker_list)  #Select ticker
tickerData = yf.Ticker(tickerSymbol)  #Get ticker data
tickerDf = tickerData.history(period='1d', start=start_date, end=end_date)
task = st.sidebar.radio('Summary', ['Profile', 'Chart', 'Historical Data'])

if task == 'Profile':
    #Ticker info <html placeholder %s> for logo image
    string_logo = '<img src=%s>' % tickerData.info['logo_url']
    st.markdown(string_logo, unsafe_allow_html=True)

    string_name = tickerData.info['longName']
    st.subheader('**%s**' % string_name)
    st.write('***%s***' % tickerData.info['sector'])

    string_summmary = tickerData.info['longBusinessSummary']
    st.info(string_summmary)
    st.write(tickerData.info['website'])
Example #24
0
def get_stock(ticker):
    stock = yf.Ticker(ticker)
    history = stock.history(period='2d', interval='1d')
    return history.to_json()
#Connects yfinance and gets historical data for stock daily price
import yfinance as yf

msft = yf.Ticker("MSFT")
print(msft)

print(msft.info)

print(msft.history(period="max"))
Example #26
0
other = pd.read_csv('otherlisted.txt', sep='|')
other = other[['ACT Symbol', 'Security Name']]
other = other.rename(columns={'ACT Symbol': 'Symbol'})
us_stocks = nasdaq.append(other)
stocks_dic = us_stocks.set_index('Symbol')['Security Name'].to_dict()

#def tick():
#    user_input = st.text_input("Enter stock symbol:", 'AAPL')

#    return user_input.upper()

tickerSymbol = str(st.text_input("Enter stock symbol:", 'AAPL'))
#get data on this ticker
for (k, v) in stocks_dic.items():
    if (tickerSymbol.upper() == k):
        tickerData = yf.Ticker(k)

        st.write("**" + "Current Stock Price of " +
                 str(tickerData.get_info()['longName']) + " is: " +
                 str(np.round(si.get_live_price(tickerSymbol), 2)) + "**")
        st.write("**" +
                 "Here's the complete Closing Price trend for this month: " +
                 "**" + str(tickerData.get_info()['longName']))

        def monthly_stock_trend_complete(tickerSymbol):
            d = pd.DataFrame()
            d = d.append(
                yf.Ticker(tickerSymbol).history(interval='1d').reset_index())
            fig = px.line(
                d,
                x="Date",
Example #27
0
def yfinanceAVG(tickersymbol):
    tickerdata = yf.Ticker(tickersymbol)
    tickerinfo = tickerdata.info
    avg = tickerinfo['fiftyDayAverage']
    return avg
Example #28
0
def get_performance(ticker_name, start_date, end_date, future_period):
    import datetime
    from datetime import timedelta, date

    #Download the data from Yfinance
    ticker = yf.Ticker(ticker_name)

    ticker_historical = ticker.history(start=start_date, end=end_date)
    ticker_historical  #Display the data

    name = ticker_name
    filename = "%s.csv" % name
    #Save data into a CSV file
    ticker_historical.to_csv(filename)

    #df.to_csv(filename)
    df = pd.read_csv(filename)

    df_days = df[['Date']]
    # print(df)

    # A variable for predicting 'n' days out into the future #'n=30' days

    # Get the Adjusted Close Price
    df = df[['Close']]

    #Create another column (the target ) shifted 'n' units up
    df['Prediction'] = df[['Close']].shift(-future_period)
    #print the new data set
    #print(df.tail())

    ### Create the independent data set (X)  #######
    # Convert the dataframe to a numpy array
    X = np.array(df.drop(['Prediction'], 1))

    #Remove the last '30' rows
    X = X[:-future_period]
    #print(X)

    ### Create the dependent data set (y)  #####
    # Convert the dataframe to a numpy array
    y = np.array(df['Prediction'])
    # Get all of the y values except the last '30' rows
    y = y[:-future_period]
    #print(y)

    # Split the data into 80% training and 20% testing
    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    # Create and train the Linear Regression  Model
    lr = LinearRegression()
    # Train the model
    lr.fit(x_train, y_train)

    # Testing Model: Score returns the coefficient of determination R^2 of the prediction.
    # The best possible score is 1.0
    lr_confidence = lr.score(x_test, y_test)
    #print("lr confidence: ", lr_confidence)

    # df['Linear Regression Accuracy'] = lr_confidence
    # Set x_forecast equal to the last 30 rows of the original data set from Adj. Close column
    x_forecast = np.array(df.drop(['Prediction'], 1))[-future_period:]
    #print(x_forecast)

    #Print linear regression model predictions for the next '30' days
    lr_prediction = lr.predict(x_forecast)
    #print(lr_prediction)

    # Create and train the Support Vector Machine (Regressor)
    svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
    svr_rbf.fit(x_train, y_train)

    # Testing Model: Score returns the coefficient of determination R^2 of the prediction.
    # The best possible score is 1.0
    rbf_svm_confidence = svr_rbf.score(x_test, y_test)
    #print("svm confidence: ", svm_confidence)

    # df['Linear Regression Accuracy'] = lr_confidence
    # Set x_forecast equal to the last 30 rows of the original data set from Adj. Close column
    x_forecast = np.array(df.drop(['Prediction'], 1))[-future_period:]
    #print(x_forecast)

    # Print support vector regressor model predictions for the next '30' days
    rbf_svm_prediction = svr_rbf.predict(x_forecast)
    #print(svm_prediction)

    # Create and train the Support Vector Machine (Regressor)
    svr_lin = SVR(kernel='linear', C=1e3, gamma=0.1)
    svr_lin.fit(x_train, y_train)

    # Testing Model: Score returns the coefficient of determination R^2 of the prediction.
    # The best possible score is 1.0
    lin_svm_confidence = svr_lin.score(x_test, y_test)
    #print("svm confidence: ", svm_confidence)

    # df['Linear Regression Accuracy'] = lr_confidence
    # Set x_forecast equal to the last 30 rows of the original data set from Adj. Close column
    x_forecast = np.array(df.drop(['Prediction'], 1))[-future_period:]
    #print(x_forecast)

    # Print support vector regressor model predictions for the next '30' days
    lin_svm_prediction = svr_lin.predict(x_forecast)
    #print(svm_prediction)

    # Create and train the Support Vector Machine (Regressor)
    svr_poly = SVR(kernel='poly', C=1e3, gamma=0.1)
    svr_poly.fit(x_train, y_train)

    # Testing Model: Score returns the coefficient of determination R^2 of the prediction.
    # The best possible score is 1.0

    x_forecast = np.array(df.drop(['Prediction'], 1))[-future_period:]

    Accuracy = {
        'Linear Regression Prediction': [lr_confidence],
        'RBF SVM Regression Prediction': [rbf_svm_confidence],
        'Linear SVM Regression Prediction': [lin_svm_confidence]
    }

    df = pd.DataFrame(Accuracy,
                      columns=[
                          'Linear Regression Prediction',
                          'RBF SVM Regression Prediction',
                          'Linear SVM Regression Prediction'
                      ])

    return df
Example #29
0
def yfBeta(tickersymbol):
    tickerdata = yf.Ticker(tickersymbol)
    tickerinfo = tickerdata.info
    beta = tickerinfo['beta']
    return beta
def stock_analysis():
  st.header("Enter the stock name")
  user_input = st.text_input("",help="Enter the ticker symbol of any stock on BSE/NSE. Ex - TCS")


  if(user_input):
      stock_name = user_input.upper()
      try:
          soup = rk.stock_data(stock_name)
          stock = yf.Ticker(stock_name+".NS")
      except:
          st.error("❗ Check your connection / Enter a valid name")
          st.stop()
      cmp = soup.find("span", class_="Number")
      #st.write("Current Market Price - ₹",cmp.text,sep='.')

      
      stock_info = get_ticker_info(stock)

      st.text("")

      #Company_description
      html1 = '''
          <html>
          <head>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
          <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <style>
          @media screen and (min-width: 601px){
              h1{
                  font-size: 30px;
              }
          }
          .jumbotron{
              background-color:#F0F2F6;
              margin-top: 50px;
          }
          img{
              position: absolute;
              z-index: 2;
              right: 20px;
              border: 5px solid grey;
              border-width: thin;
              top: -110px;
              box-shadow: 1px 1px 3px 0.5px;
          }
          .container{
            paddin
          }
          </style>
          </head>        
          <body>
          <main role="main">
          <!-- Main jumbotron for a primary marketing message or call to action -->
          <div class="jumbotron">

      <div style="position: relative; z-index: 1;">
      <img src=%s style="position: absolute; z-index: 2;" />

      </div>
              <div class="container">
              <h1 class="display-3">%s</h1>
              <p style="font-weight: 500;margin-bottom: 32px;">Industry >> %s</p>
              <p><h5><span style="color: white;" class="sc-hover badge bg-dark" data-cardsize="small" data-quantity="2" data-ordertype="BUY">%s</span></h5>%s</p><br>
              <p><a class="btn btn-primary btn-lg" href=%s role="button" target="_blank">Learn more &raquo;</a></p>
              </div>
          </div>
          </main>
          <script async src="https://www.gateway-tt.in/assets/embed.js"></script>
          </body>
      </html>
      ''' %(stock_info['logo_url'],stock_info['longName'],stock_info['industry'],stock_name,stock_info['longBusinessSummary'],stock_info['website'])
      components.html(html1,height=720)
      
      #Financial info
      c1,c2,c3 = st.beta_columns(3)

      with c1:
          '''
          ### Market Cap: ₹**%d Cr.**
          ### EPS: ₹**%.2f**
          ### Book Value: ₹**%.2f **
          ### Stock PE: ** %.2f **
          ### Beta: ** %.2f **
          ''' %(stock_info['marketCap']//10000000,stock_info['trailingEps'],stock_info['bookValue']*70,stock_info['trailingPE'],stock_info['beta'])


      with c2:
          '''
          ### Earnings Growth(QoQ):** %.2f%% ** 
          ### Forward PE:** %.2f **
          ### Forward EPS: ₹**%.2f**
          ### Sector:** %s **
          ### 50 DMA: ₹**%.2f **
          ''' %(stock_info['earningsQuarterlyGrowth']*100,stock_info['forwardPE'],stock_info['forwardEps'],stock_info['sector'],stock_info['fiftyDayAverage'])


      with c3:
          '''
          ### 52 Week High / Low: ₹**%.2f / %.2f **
          ### Promoter Holding:** %.2f%% **
          ### Dividend Yield:** %.2f%% **
          ### 200 DMA: ₹**%.2f **
          ### CMP: ₹**%s ** 
          
          ''' %(stock_info['fiftyTwoWeekHigh'],stock_info['fiftyTwoWeekLow'],stock_info['heldPercentInsiders']*100,stock_info['dividendYield']*100,stock_info['twoHundredDayAverage'],cmp.text)

      ''' ***** '''
      st.text("")

      # strength & limitations
      col1, col2 = st.beta_columns(2)

      #Strengths
      col1.header("Strengths")
      strength = soup.find("ul", class_="strength").text
      strength = strength.strip().replace('\n','  \n')
      if strength=='':
        col1.success('No Strength')
      else:
        col1.success(strength)

      #Limitations
      col2.header("Limitations")
      limitations = soup.find("ul", class_="limitations").text
      limitations = limitations.strip().replace('\n','  \n')
      if limitations=='':
            col2.error("No Limitations")
      else:
            col2.error(limitations)
      
      #Price Chart
      st.text("")
      st.header("Price Chart")
      ticker = user_input
      new_ticker = '\"'+'BSE:'+ticker+'\"'
      chart='''
      <!-- TradingView Widget BEGIN -->
      <div class="tradingview-widget-container">
        <div id="basic-area-chart"></div>
        <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/'''+ticker+'''/" rel="noopener" target="_blank"><span class="blue-text">'''+ticker+''' Chart</span></a> by TradingView</div>
        <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
        <script type="text/javascript">
        new TradingView.widget(
        {
        "container_id": "basic-area-chart",
        "width": 1200,
        "height": 700,
        "symbol": '''+new_ticker+''',
        "interval": "D",
        "timezone": "exchange",
        "theme": "light",
        "style": "3",
        "toolbar_bg": "#f1f3f6",
        "hide_top_toolbar": true,
        "save_image": false,
        "locale": "en"
      }
        );
        </script>
      </div>
      <!-- TradingView Widget END -->
      '''
      components.html(chart,width=1400,height=700)

      #Annual Report
      reports = rk.balance_sheet(stock_name)
      annual_report = reports[1].rename(columns={'Unnamed: 0':' '})
      if 'TTM' in annual_report.columns:
          annual_report.drop('TTM',axis=1,inplace=True)
      years=np.array(annual_report.columns[1:])
      years= [int(item.split()[1]) for item in years]

      revenue=annual_report.iloc[0][1:]
      revenue = [int(item) for item in revenue]

      #Revenue (YOY)
      st.text("")
      st.header("Revenue (YOY) in Cr.")
      c=alt.Chart(pd.DataFrame({"Revenue":revenue,"Year":years})).mark_bar(size=50).encode(x='Year:O',y='Revenue',tooltip=['Revenue','Year'],opacity=alt.value(0.7),
      color=alt.value('#26c6da')).configure_view(strokeWidth=0).properties(height=500)
      st.altair_chart(c,use_container_width=True)

      #Profit (YOY)
      profit=annual_report.iloc[9][1:]
      profit = [int(item) for item in profit]

      st.text("")
      st.header("Profits (YOY) in Cr.")
      c=alt.Chart(pd.DataFrame({"Profit":profit,"Year":years})).mark_bar(size=50).encode(x='Year:O',y='Profit',tooltip=['Profit','Year'],opacity=alt.value(0.7),
      color=alt.value('#48e421')).configure_view(strokeWidth=0).properties(height=500)
      st.altair_chart(c,use_container_width=True)

      #Balance Sheet
      st.text("")
      st.header("Balance Sheet")
      balance_sheet = reports[6].rename(columns={'Unnamed: 0':' '})
      st.write(balance_sheet)

      #Shareholding pattern
      st.text("")
      st.header("Shareholding Pattern ")
      shareholders = list(reports[9]['Unnamed: 0'])
      shareholders = [i.rstrip("\xa0+") for i in shareholders]
      shareholding = list(reports[9][reports[9].columns[-1]])

      col1, col2, col3 = st.beta_columns([1,2,1])

      col1.write("")

      col2.vega_lite_chart(pd.DataFrame({'Shareholders':shareholders,'Shareholding':shareholding}), {
      "width": 600,
      "height": 600,
      "encoding": {
      "theta": {"field": "Shareholding", "type": "quantitative", "stack": True},
      "color": {"field": "Shareholders", "type": "nominal"},
      "tooltip": {"field": "Shareholding", "type": "quantitative"}
      },
      "layer": [{
          "mark": {"type": "arc", "outerRadius": 150}
      }, {
          "mark": {"type": "text", "radius": 190},
          "encoding": {
          "text": {"field": "Shareholders", "type": "nominal"}
          }
      }]
      })

      col3.write("")

      
      #Competitor analysis
      st.text("")
      st.header("Comparison with other stocks")
      stocks=[]
      stocks.append(stock.history(period="20y"))

      user_input2 = st.text_input("Enter stock 1",help="Enter a stock to compare with"+user_input)
      if user_input2!='':
          stock1 = yf.Ticker(user_input2.upper()+".NS")
          stocks.append(stock1.history(period="20y"))
          if (stocks[1].empty):
                  st.error("Error.....Incorrect")
                  st.stop()

      user_input3 = st.text_input("Enter stock 2",help="Enter a stock to compare with"+user_input)
      if user_input3!='':
          stock2 = yf.Ticker(user_input3.upper()+".NS")
          stocks.append(stock2.history(period="20y"))
          if (stocks[2].empty):
                  st.error("Error.....Incorrect")
                  st.stop()


      if user_input2!='' and user_input3!='':

        stocks[0]['symbol']=user_input
        stocks[1]['symbol']=user_input2
        stocks[2]['symbol']=user_input3
        #st.write(stocks[0].tail(5))
        df = pd.concat([s[['Close','Volume','symbol']] for s in stocks])
        df.reset_index(level=0, inplace=True) #make Date a column instead of index
        st.text("")
        st.header("Comparative Price Chart")
        c=alt.Chart(df,height=650).mark_line().encode(
        x='Date',
        y='Close',
        color='symbol',
        tooltip=alt.Tooltip(['Close'], format='.2f',title='INR')
        ).interactive()
        st.altair_chart(c,use_container_width=True)
        
        #volume
        st.text("")
        st.header("Traded Volumes")
        selection = alt.selection_multi(fields=['symbol'], bind='legend')
        c=alt.Chart(df,height=650).mark_line().encode(
        x='Date',
        y='Volume',
        color='symbol',
        tooltip=alt.Tooltip(['Volume']),
        opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
        ).add_selection(selection)
        st.altair_chart(c,use_container_width=True)

        #Histogram
        st.text("")
        st.header("Daily Percentage Change")
        col1, col2, col3 = st.beta_columns(3)
        for i,col,name in (zip(range(3),[col1,col2,col3],[user_input,user_input2,user_input3])):
            stocks[i]['Returns']=stocks[i]['Close'].pct_change(1)
            col.altair_chart(alt.Chart(stocks[i]).mark_bar().encode(
                x=alt.X("Returns:Q", bin=alt.Bin(extent=[-0.100,0.100],step=0.005),title=name),
                y=alt.Y(aggregate="count",title="",type="quantitative")
            ).properties(height=500).interactive(),use_container_width=True)

        #Scatter Matrix
        st.text("")
        st.header("Scatter Matrix - (Finding Correlation)")
        st.text("")
        box_df = pd.concat([stocks[0]['Returns'],stocks[1]['Returns'],stocks[2]['Returns']],axis=1)
        box_df.columns = [user_input+" Returns",user_input2+" Returns",user_input3+" Returns"]
        st.altair_chart(alt.Chart(box_df).mark_circle().encode(
            alt.X(alt.repeat("column"), type='quantitative'),
            alt.Y(alt.repeat("row"), type='quantitative'),
            color='Origin:N'
        ).properties(
            width=385,
            height=185
        ).repeat(
            row=list(box_df.columns),
            column=list(box_df.columns[::-1])
        ).interactive(),use_container_width=True)