예제 #1
0
def main():
    listy = gt.get_tickers()
    with open('../stocklist.csv', "w") as outfile:
        for entries in listy:
            if getdailydata(entries) == 'cool':
                outfile.write(entries)
                outfile.write("\n")
예제 #2
0
    def handle(self, *args, **kwargs):
        list_of_tickers = gt.get_tickers()
        for tickername in list_of_tickers:
            print(tickername)
            try:
                ticker = yf.Ticker(tickername)

                tags = {'longName': '',
                        'country': '',
                        'website': '',
                        'sector': '',
                        'industry': '',
                        'fullTimeEmployees': 0}

                for tag in tags:
                    try:
                        tags[tag] = ticker.info[tag]
                    except KeyError:
                        pass

                print(tags)

                if tags['longName'] != '':
                    Company.objects.get_or_create(name=tags['longName'],
                                                  country=tags['country'],
                                                  web=tags['website'],
                                                  sector=tags['sector'],
                                                  industry=tags['industry'],
                                                  employees_count=tags['fullTimeEmployees'])
            except:
                pass
예제 #3
0
def buy_stock(user_id,qty,symbol,price):
    curr= conn.cursor()
    user= (user_id)
    list_of_tickers = gt.get_tickers()
    flag = True
    for i in list_of_tickers:
        if(i ==symbol):
            flag = True
    if flag == True:
        curr.execute("""Select cash from user_money where user_id = ?;""",(user_id,))
        um=curr.fetchall()
        um =str(um)
        price =str(price)
        pr = price.replace(',' ,'')
        p=float(pr)
        qty=float(qty)
        commsion = float(0.01 *(qty*p))
        total =qty*p
        print(um)
        print(user_id)
        um=float(um.strip("([,])"))
        if(total +commsion > um):
            print("error")
            messagebox.showerror("Error", "your dont have enough balance")
        else:
            print("trading")
            curr.execute("""Select cash from user_money where user_id = ?;""",(user_id,))
            trade(conn,user_id,symbol,qty,"buy",p)
    else:
        messagebox.showerror("Error", "Symbol Not found")
예제 #4
0
def main():
    symbols = gt.get_tickers(NYSE=True, NASDAQ=True, AMEX=True)
    for i, chunk in enumerate(chunks(symbols, 200), start=1):
        get_all(chunk)

        sql = f"""
                  INSERT INTO yahoo_stock_data
                    (SELECT t.date,
                            t.low,
                            t.close,
                            t.open,
                            t.high,
                            t.volume,
                            t.adjclose,
                            t.dividends,
                            t.symbol,
                            t.splits
                     FROM temp_yahoo_stock_data t
                     WHERE NOT EXISTS(SELECT *
                                      FROM yahoo_stock_data y
                                      WHERE t.symbol = y.symbol
                                        and t.date = y.date))
            """
        res = pg_db.query(sql)
        print(f'finished {i} batch = {i * 200}')
예제 #5
0
def stock_his():
    symbol = askstring('Symbol', 'Enter Symbol')
    list_of_tickers = gt.get_tickers()
    flag = False
    for i in list_of_tickers:
        if(i ==symbol):
            flag = True
        if flag == True:
            StockHistory(symbol)
예제 #6
0
def main():
    key = 'PjeqU9zauMH9o49WYWurfZslqfY8HpF7'
    #API CALL
    with RESTClient(key) as client:
        ''' This block is for reference purposes only
        # Note that Q results are off by 1 fiscal year, bug currently being worked on
        resp = client.stocks_equities_daily_open_close("AAPL","2018-03-02")
        print(f"on: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}")
        resp = client.reference_stock_financials("MSFT",limit=1,type='Q')
        print(f"MSFT market cap is {resp.results[0].get('marketCapitalization')} as reported on {resp.results[0].get('reportPeriod')}.")
        custom_limit=100
        resp = client.reference_stock_financials("MSFT",limit=100,type='Q')
        for i in range(custom_limit):
            print('*'*50)
            print(f"MSFT market cap is {resp.results[i].get('marketCapitalization')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT debt to equity ratio is {resp.results[i].get('debtToEquityRatio')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT divident yield is {resp.results[i].get('dividendYield')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT gross profit is {resp.results[i].get('grossProfit')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT net income is {resp.results[i].get('netIncome')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT revenues in USD is {resp.results[i].get('revenuesUSD')} as reported on {resp.results[i].get('reportPeriod')}.")
            print(f"MSFT operating income is {resp.results[i].get('operatingIncome')} as reported on {resp.results[i].get('reportPeriod')}.")
            print('*'*50)

        print("Testing completed for stock financials. Beginning testing for databasing.")
        print("="*50)
        '''

        #Get a list of all tickers
        list_of_all_tickers = gt.get_tickers(NYSE=True,
                                             NASDAQ=True,
                                             AMEX=False)

        #Set flags to keep track of db initializations
        DB_EXISTENCE_FLAGS = [False, False, False]

        #Initialize the root db
        if os.path.isfile("Root_Database.csv"):
            print("Root DB found, aborting init operation.")
        else:
            if (init_root_db(list_of_all_tickers)):
                DB_EXISTENCE_FLAGS[0] = True
                print("Root DB has been successfully initialized.")
            else:
                print("Root DB initialization has failed.")

        #Initialize the info db
        if os.path.isfile("Info_Database1.csv"):
            print("Info DB found, aborting init operation.")
        else:
            if (init_info_db(key, list_of_all_tickers)):
                DB_EXISTENCE_FLAGS[1] = True
                print("Info DB has been successfully initialied.")
            else:
                print("Info DB initialization has failed.")
예제 #7
0
 def mentions_by_ticker(self) -> dict:
     ticker_mentions = {}
     tickers = set(gt.get_tickers())
     for message in self.messages:
         # split message to look for tickers
         message_by_parts = message["content"].split(" ")
         # in_message is mentioned tickers
         in_message = set(message_by_parts).intersection(tickers)
         date = datetime.strptime(message["timestamp"].split('T')[0], '%Y-%m-%d')
         # map by date, messages
         ticker_mentions[date] = ticker_mentions.get(date, TickersByDate(date)).add_tickers(in_message, message)
     return ticker_mentions
예제 #8
0
 def __init__(self, tick):
     """
         The constructor takes in a stock tick symbol and 
         initialize the member variables if the symbol is valid.
         If the symbol is invalid, an exception will be raised.
     """
     tickerList = set(gt.get_tickers())
     if tick not in tickerList:
         errorMessage = "Invalid stock tick symbol {}, please double check.".format(
             tick)
         raise Exception(errorMessage)
     self.stock = yf.Ticker(tick)
     self.tick = tick
예제 #9
0
def generate_rss_yahoo_csv(
        save_to="./resource/rss_yahoo_us_stock.csv",
        symbol_path=None) -> None:

    if symbol_path is None:
        from get_all_tickers.get_tickers import get_tickers
        symbols = get_tickers()
    else:
        symbols = pd.read_csv(symbol_path, header=None)[0]

    urls = [
        f"http://finance.yahoo.com/rss/headline?s={s}" for s in symbols]
    df = pd.DataFrame({
        "ticker": symbols,
        "url": urls,
    })
    df.to_csv(save_to, index=False)
예제 #10
0
def get_stock_squeeze_list():
    squeeze_list = []
    symbols = gt.get_tickers(NYSE=True, NASDAQ=True, AMEX=True)
    for symbol in symbols:
        df = MyYahoo.get_stock_data_db(symbol)
        if len(df) > 120 and breaking_out_of_squeeze(df):
            print(f"{symbol} is coming out the squeeze")
            squeeze_list.append(dict(symbol=symbol))
    if squeeze_list:
        with open(
                f"{Path(__file__).parent.absolute()}/results/squeeze_list.json",
                'w') as fp:
            recipient, message, subject = [
                '*****@*****.**',
                f'yahoo stock squeeze list successfully generated at {datetime.now()}',
                'squeezed'
            ]
            send_eri_mail(recipient, message, subject)
            json.dump(squeeze_list, fp)
            return True
예제 #11
0
    def generate(self):
        report = open("report.txt", "w")
        input_smaDay = int(self.plainTextEdit.toPlainText())
        input_rsi_high = int(self.plainTextEdit_2.toPlainText())
        input_rsi_low = int(self.plainTextEdit_6.toPlainText())
        input_max_days = int(self.plainTextEdit_4.toPlainText())
        input_amplification = float(self.plainTextEdit_5.toPlainText())
        input_checkForSell = self.plainTextEdit_3.toPlainText()

        downloadStartDate = dt.datetime.now() - dt.timedelta(
            days=input_smaDay * 2 + 16)
        TenWeeksAgoDate = dt.datetime.now() - dt.timedelta(days=70)
        downloadEndDate = dt.datetime.now()

        print("Start generating Sell report ......")
        report.write("--------------- SELL LIST ---------------\n")
        input_checkForSellList = input_checkForSell.split(",")
        sellcount = 0
        for i in range(0, len(input_checkForSellList)):
            try:
                isSell = False
                print("Checking for " + input_checkForSellList[i])
                df = yf.download(input_checkForSellList[i],
                                 downloadStartDate,
                                 downloadEndDate,
                                 interval='1d')
                if (df.empty):
                    continue
                lastDayPrice = df["Close"].iloc[-1]

                sma = df.rolling(window=input_smaDay).mean()

                if (df["High"].iloc[-1] > sma["Close"].iloc[-1]
                        and df["Low"].iloc[-1] < sma["Close"].iloc[-1]):
                    isSell = True

                stock = stockstats.StockDataFrame.retype(df)
                rsi = stock["rsi_14"]
                if (rsi.iloc[-1] > 62):
                    isSell = True

                if (isSell):
                    sellcount = sellcount + 1
                    print("Added to sell list :" + input_checkForSellList[i])
                    report.write(str(sellcount) + " ********************\n")
                    report.write("Stock: " + input_checkForSellList[i] + "\n")
                    report.write("Current Price: " + str(lastDayPrice) + "\n")

                    df10w = yf.download(input_checkForSellList[i],
                                        TenWeeksAgoDate,
                                        downloadEndDate,
                                        interval='1d')
                    report.write("10 weeks high: " + str(df10w["High"].max()) +
                                 "\n")
                    report.write("10 weeks low: " + str(df10w["Low"].min()) +
                                 "\n")
                    report.write("RSI: " + str(rsi.iloc[-1]) + "\n")
                    report.write("SMA: " + str(sma["Close"].iloc[-1]) + "\n")
                    report.write("Today's volume: " +
                                 str(df10w["Volume"].iloc[-1]) + "\n")
                    report.write("Average volume: " +
                                 str(df10w["Volume"].mean()) + "\n")
                    marketCap = data.get_quote_yahoo(
                        input_checkForSellList[i])['marketCap']
                    report.write("Market capital: " +
                                 str(millify(marketCap, precision=2)) + "\n")
                    report.flush()
            except:
                continue

        print("Start generating Buy report ......")
        report.write("\n--------------- BUY LIST ---------------\n")

        stocksList = gt.get_tickers()
        buyCount = 0
        for i in range(0, len(stocksList)):
            print("Checking for " + stocksList[i])
            try:
                marketCap = data.get_quote_yahoo(stocksList[i])['marketCap']
                if (marketCap.values[0] < 2000000000):
                    print("Market cap below 2B BBBBBBBBBBBBBBBB")
                    continue
                df = yf.download(stocksList[i],
                                 downloadStartDate,
                                 downloadEndDate,
                                 interval='1d')
                if (df.empty):
                    print("df is empty yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
                    continue
                lastDayPrice = df["Close"].iloc[-1]
                sma = df.rolling(window=input_smaDay).mean()
                if (df["Low"].iloc[-1] < sma["Close"].iloc[-1]):
                    print(
                        "last day lowest below SMA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    )
                    continue
                if (df["Close"].iloc[-1] < 6):
                    print(
                        "less than 5$ 5555555555555555555555555555555555555555555555555555555555"
                    )
                    continue

                stock = stockstats.StockDataFrame.retype(df)
                rsi = stock["rsi_14"]
                if (rsi.iloc[-1] > input_rsi_high):
                    print(
                        "rsi too high hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
                    )
                    continue
                if (rsi.iloc[-1] < input_rsi_low):
                    print(
                        "rsi too low lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll"
                    )
                    continue
                if (rsi.iloc[-1] < rsi.iloc[-3]):
                    print(
                        "2 days ago > today rsi 22222222222222222222222222222222222222222222222222222222222222222222222222222222"
                    )
                    continue
                xDaysAgoDate = dt.datetime.now() - dt.timedelta(
                    days=input_max_days)
                dfXDays = yf.download(stocksList[i],
                                      xDaysAgoDate,
                                      downloadEndDate,
                                      interval='1d')
                if (dfXDays["High"].max() <
                        input_amplification * dfXDays["Close"].iloc[-1]):
                    print(
                        "Max < current stock MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
                    )
                    continue

                buyCount = buyCount + 1
                print(
                    "Added to buy list :" + stocksList[i] +
                    " ///////////////////////////////////////////////////////////////////////////////////////////"
                )
                report.write(str(buyCount) + " ********************\n")
                report.write("Stock: " + stocksList[i] + "\n")

                report.write("Current Price: " + str(lastDayPrice) + "\n")
                df10w = yf.download(stocksList[i],
                                    TenWeeksAgoDate,
                                    downloadEndDate,
                                    interval='1d')
                report.write("10 weeks high: " + str(df10w["High"].max()) +
                             "\n")
                report.write("10 weeks low: " + str(df10w["Low"].min()) + "\n")
                report.write("RSI: " + str(rsi.iloc[-1]) + "\n")
                report.write("SMA: " + str(sma["Close"].iloc[-1]) + "\n")
                report.write("Today's volume: " +
                             str(df10w["Volume"].iloc[-1]) + "\n")
                report.write("Average volume: " + str(df10w["Volume"].mean()) +
                             "\n")
                report.write("Market capital: " +
                             str(millify(marketCap, precision=2)) + "\n")
                report.flush()
            except:
                print("Exception")
                continue

        report.close()
예제 #12
0
# import the modules
import praw
import pandas as pd
from authenticate import redditAuthenticate
from get_all_tickers import get_tickers as gt

# creating an authorized reddit instance
reddit = redditAuthenticate()

#get tickers and remove duplicates (listed on multiple exchanges?)
tickers = list(dict.fromkeys(gt.get_tickers()))

#WSB lingo
lingo = [
    'I', 'A', 'DD', 'WSB', 'LOL', 'IV', 'IP', 'YOLO', 'TIL', 'EDIT', 'OTM',
    'GOT', 'IPO', 'WTF', 'ATH'
]

#ignore WSB lingo
filteredTickers = [ele for ele in tickers if ele not in lingo]

#fetch daily discussion thread
#submission = next(reddit.subreddit("wallstreetbets").search("title:Daily Discussion Thread for AND flair:Daily Discussion", time_filter='day'))
submission = next(
    reddit.subreddit("wallstreetbets").search(
        "title:What Are Your Moves Tomorrow AND flair:Daily Discussion",
        time_filter='day'))
print(submission.title)

#add limit=X to scrap first X pages only
submission.comments.replace_more()
예제 #13
0
def get_ticker_list():
    ticker_filter = re.compile('^[A-Z]+$')
    master_ticker_list = gt.get_tickers()
    master_ticker_list = [x for x in master_ticker_list if ticker_filter.match(x)]
    return master_ticker_list
예제 #14
0
import pandas as pd
import numpy as np

import logging

APCA_API_BASE_URL = "https://paper-api.alpaca.markets"

# Initializing Firestore
cred = credentials.Certificate('service_account.json')
firebase_admin.initialize_app(cred)

db = firestore.client()

# Get all Tickers
tickers = gt.get_tickers(NYSE=True, NASDAQ=True, AMEX=True)

print(tickers)

# Get Data for the past 30 days for all tickers
data = get_data_month(tickers=tickers)

print(data)

# store = pd.HDFStore('data.h5')
# # store['new_data'] = data

# data = store['new_data']

last_empty = True
예제 #15
0
def get_nyse():
    nyse_tickers = get_tickers.get_tickers(NYSE=True, NASDAQ=False, AMEX=False)
    return nyse_tickers
예제 #16
0
import sys
from get_all_tickers import get_tickers as gt
import subprocess
import re

EXCLUDED_SYMBOLS = [
    "CBO", "CBX", "CELG~", "GIX~", "AUUD", "AUUDW", "BIOTU", "BTNB", "BCACU",
    "JAQCU", "MVNR", "NLSP", "NLSPW", "SPEL"
]

fields = ["High", "Low", "Open", "Close"]
pattern = ""
for field in fields:
    pattern += field + ": [\d,]*\d(\.\d+)?\s*"  # Output must be a number

symbols = gt.get_tickers()

print(symbols)

errored_symbols = []
for i in range(len(symbols)):
    symbol = symbols[i].strip()
    if symbol in EXCLUDED_SYMBOLS:
        continue
    try:
        out = subprocess.check_output(["py", "scrape.py", symbol])  # Expensive
        if not re.match(pattern, out.decode('utf8')):
            print("Output for symbol " + symbol + " is NaN", file=sys.stderr)
            errored_symbols.append(symbol)
    except subprocess.CalledProcessError as e:
        print("Error when fetching data for symbol " + symbol, file=sys.stderr)
예제 #17
0
import stock_quality_score as qs
from get_all_tickers import get_tickers as gt
import warnings
warnings.filterwarnings("ignore")

# some example tickers
my_tickers = ['AAPL', 'MCD', 'SAP']
result = qs.quality_scores_30y(tickers=my_tickers)

# all unique tickers
all_tickers = gt.get_tickers()
all_tickers = list(set(all_tickers))
result = qs.quality_scores_30y(tickers=all_tickers)  # takes long time

# calculate sum of decade scores and sort
result['score_sum'] = result.fillna(0).score_1990s + result.fillna(
    0).score_2000s + result.fillna(0).score_2010s
result = result.sort_values(by='score_sum', ascending=False)
예제 #18
0
from get_all_tickers import get_tickers as gt
import pandas as pd
import csv

df = pd.read_csv("secwiki_tickers.csv")
dp = pd.read_csv("tickers.csv", names=["pTicker"])
list_of_tickers = gt.get_tickers()
# or if you want to save them to a CSV file
gt.save_tickers()
tmpTickers = []
stocks = []
for i in range(len(list_of_tickers)):
    test = df[df.Ticker == list_of_tickers[i]]
    if not (test.empty):
        stocks.append((list_of_tickers[i], list(test.Name.values)[0]))

with open("stocks.csv", "w", newline="") as csv_file:
    fieldnames = ["ticker", "name"]
    writer = csv.writer(csv_file)
    writer.writerows(stocks)
예제 #19
0
    def allTickers(self):
        list = gt.get_tickers()

        return list
예제 #20
0
 def mentions_by_ticker(self) -> dict:
     tickers_mentions = {}
     tickers = gt.get_tickers()
     return tickers_mentions
 def handle(self, *args, **kwargs):
     list_of_tickers = gt.get_tickers()
     for ticker in list_of_tickers:
         print(ticker)
         Ticker.objects.get_or_create(name=ticker, company=Company(id=1))
예제 #22
0
        report.write("10 weeks high: " + str(df10w["High"].max()) + "\n")
        report.write("10 weeks low: " + str(df10w["Low"].min()) + "\n")
        report.write("RSI: " + str(rsi.iloc[-1]) + "\n")
        report.write("SMA: " + str(sma["Close"].iloc[-1]) + "\n")
        report.write("Today's volume: " + str(df10w["Volume"].iloc[-1]) + "\n")
        report.write("Average volume: " + str(df10w["Volume"].mean()) + "\n")
        marketCap = data.get_quote_yahoo(
            input_checkForSellList[i])['marketCap']
        report.write("Market capital: " +
                     str(millify(marketCap, precision=2)) + "\n")
        report.flush()

print("Start generating Buy report ......")
report.write("\n--------------- BUY LIST ---------------\n")

stocksList = gt.get_tickers()
input_rsi_high = 200
input_rsi_low = 5
input_max_days = 50
input_amplification = 0.8
buyCount = 0
for i in range(0, len(stocksList)):
    print("Checking for " + stocksList[i])
    try:
        marketCap = data.get_quote_yahoo(stocksList[i])['marketCap']
    except:
        print("exception")
        continue
    if (marketCap.values[0] < 2000000000):
        print("Market cap below 2B BBBBBBBBBBBBBBBB")
        continue
예제 #23
0
from flask import Flask, render_template, request, redirect
import os
import io
import base64
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import pandas as pds
import requests
import simplejson as json
#this list does not seem to be exhaustive, but is the best I could find
from get_all_tickers import get_tickers as gt
list_of_all_tickers = gt.get_tickers()

app = Flask(__name__)


@app.route('/')
def subform():
    #landing page with submission form
    return render_template('subform.html')


@app.route('/image', methods=['GET', 'POST'])
def image():
    if request.method == 'GET':
        #suggest that users hit up landing page directly
        return render_template("landing_error.html")
    if request.method == 'POST':
        #get stock ticker symbol from submission on landing page
        tickersym = request.form['Name']
        #check if the input is a valid U.S. stock ticker symbol
예제 #24
0
def verify_info_database(currentTickerList):
    return 1


# Update the info database
# Jump to each ticker in changeList and do operation based on opcode
# Args: changeDict<Dict>
# Returns 1 on success, else returns 0
def update_info_database(changeDict):
    return 1


# Main

# Put all tickers in a list
list_of_all_tickers = gat.get_tickers(NYSE=True, NASDAQ=True, AMEX=False)

# Initialize the root DB csv file
# -Once initialized and the csv database is created,
#       1. init_root_database should never be called again
#       2. The root database should only be read from once created
#           -Dynamically updating the database is too complicated and outside of scope for now

DB_EXISTENCE_FLAGS = [False, False, False]

if os.path.isfile("Root_Database.csv"):
    print("Root DB found.")
else:
    if (init_root_database(list_of_all_tickers)):
        DB_EXISTENCE_FLAGS[0] = True
        print("Root DB has been successfully initialized.")
예제 #25
0
def get_amex():
    amex_tickers = get_tickers.get_tickers(NYSE=False, NASDAQ=False, AMEX=True)
    return amex_tickers
예제 #26
0
 def tickerList(self, dlTickers):
     """Import all NYSE tickers"""
     if dlTickers:
         list = gt.get_tickers()
     return list
예제 #27
0
def get_nasdaq():
    nasdaq_tickers = get_tickers.get_tickers(NYSE=False,
                                             NASDAQ=True,
                                             AMEX=False)
    return nasdaq_tickers