Exemplo n.º 1
0
def get_stock_moving_average():
    msft = yf.Ticker("MSFT")
    day_to_day_price = []
    day_to_day_sell = []
    day_to_day_buy = []
    buy_day_price = []
    sell_day_price = []
    days = []
    buy_limit = 20
    buy = 0
    sell = 0
    coin = 0
    profit = 0
    value = msft.history(period="max")["Open"]
    bank = 2000
    n = 50
    day = 0
    total_for_n = 0
    days_from_start = 0
    while (days_from_start < len(msft.history(period="max")["Open"])):
        price = value[days_from_start]
        if days_from_start >= n:
            front_window_price = value[days_from_start - n]
            day_to_day_price.append(front_window_price)
            days.append(days_from_start - n)
            average = total_for_n / n
            total_for_n = total_for_n - front_window_price
            if average > price:
                buy = buy + 1
                profit = profit - buy_limit
                bank = bank - buy_limit
                if profit > 0:
                    print("price: " + str(price))
                    print("buy profit: " + str(profit))
            elif average < price:
                sell = sell + 1
                profit = profit + buy_limit
                bank = bank + buy_limit
                if profit > 0:
                    print("price: " + str(price))
                    print("sell profit: " + str(profit))
        total_for_n = total_for_n + price
        days_from_start = days_from_start + 1
    print("this is the profit using this algorithm: " + str(profit))
    print("shares bought: " + str(coin))
    print("coins value: " +
          str(coin * r.json()['bpi'][str(today - timedelta(days=1))]))
    print("total over all value: " +
          str(profit +
              (coin * r.json()['bpi'][str(today - timedelta(days=1))])))
    print("bank: " + str(bank))
    print("sell: " + str(sell))
    print("buy: " + str(buy))
    items = {"prices": day_to_day_price, "days": days}
    return items
Exemplo n.º 2
0
def simple_quotes(av_key, filePath, symbol_list):
    import requests
    import csv
    import sys
    import time
    from datetime import datetime
    processed_count = 0
    total_symbols = len(symbol_list)
    symbols_remaining = total_symbols
    print("")
    print("Total number of symbols to update: ", total_symbols)
    print("")
    try:
        for symbol in symbol_list:
            oldepoch = time.time()
            start_time = datetime.now()
            processed_count_continuous = 0
            rate_limit_begin_time = time.time()
            processed_count = processed_count+1
            processed_count_continuous = processed_count_continuous+1
            payload = {'function': 'GLOBAL_QUOTE', 'symbol': symbol, 'apikey': av_key}
            r = requests.get('https://www.alphavantage.co/query', params=payload)
            data_json = r.json()
            _open = str(data_json['Global Quote']['02. open'])
            high = data_json['Global Quote']['03. high']
            low = data_json['Global Quote']['04. low']
            close = data_json['Global Quote']['05. price']
            volume = data_json['Global Quote']['06. volume']
            #latest_trading_day = data_json['Global Quote']['07. latest trading day']
            #previous_close = data_json['Global Quote']['08. previous close']
            change = data_json['Global Quote']['09. change']
            change_percentage = data_json['Global Quote']['10. change percent']
            print(symbol, ": ", change, "  ", change_percentage)
            fileName = symbol + ".csv"
            _date = datetime.today().strftime('%Y-%m-%d')
            with open(filePath + fileName, mode='w') as csv_file:
                csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                csv_writer.writerow(['date', '1. open', '2. high', '3. low', '4. close', '5. volume'])
                csv_writer.writerow([_date, _open, high, low, close, volume])
            symbols_remaining = symbols_remaining-1
            if minute_passed(oldepoch) or processed_count == 5:
                rate_limit_end_time = time.time()
                time_passed = rate_limit_end_time - rate_limit_begin_time
                pause_time = 60 - time_passed
                processed_count = 0
                print("*** Pausing for ", pause_time, " seconds.")
                print("*** ", symbols_remaining, " symbols remain.")
                time_passed = datetime.now() - start_time
                print("*** This download has been running for ", time_passed)
                download_rate = time_passed / processed_count_continuous
                estimated_time_remaining = symbols_remaining * download_rate
                print("*** Estimated time remaining: ", estimated_time_remaining)
                est_end_time = datetime.now() + estimated_time_remaining
                print("*** Estimated end time: ", est_end_time)
                print("")
                time.sleep(pause_time)
                oldepoch = time.time()
    except Exception as e:
        sys.exit(e)
Exemplo n.º 3
0
def get_watchlist_symbols(email, password, rh_watchlist):
    import sys
    import csv
    import requests
    import robin_stocks as r
    try:
        r.login(email, password)
        watchlist = r.get_watchlist_by_name(name=rh_watchlist, info=None)
        watchlistsymbols = []
        for item in watchlist:
            url = item['instrument']
            r = requests.get(url)
            data_json = r.json()
            # print(str(data_json))  # print this to see more symbol info.
            watchlistsymbols.append(data_json['symbol'])
        # put watchlist into a file if
        return(watchlistsymbols)
    except Exception as e:
        sys.exit(e)
Exemplo n.º 4
0
def bitcoin_moving_average_historical():
    items = {}
    day_to_day_bc_price = []
    day_to_day_bc_sell = []
    day_to_day_bc_buy = []
    buy_day_price = []
    sell_day_price = []
    days = []
    coinbase_key = os.environ['COINBASE_API_KEY']
    coinbase_secret = os.environ['COINBASE_API_SECRET']
    print(coinbase_key)
    print(coinbase_secret)
    client = Client(coinbase_key, coinbase_secret)
    account = client.get_primary_account()
    total = 0
    count = 0
    averagePrice = 0
    dayEstimate = 0
    currentPrice = client.get_buy_price(currency_pair='BTC-USD')
    currentPrice = currentPrice.get("amount")
    #If this is too large it'll throw 404
    time_to_track = 500
    today = datetime.today().date()
    print("this is today: " + str(today))
    end = today - timedelta(days=time_to_track)
    print("this is end: " + str(end))
    "Coindesk API get request to query legacy information on day scale"
    r = requests.get(
        "https://api.coindesk.com/v1/bpi/historical/close.json?start=" +
        str(end) + "&end=" + str(today) + "")
    print("this is response: " + str(r))
    dates = r.json()['bpi'][str(end)]
    print("this is the date:" + str(dates))
    buy_limit = 20
    buy = 0
    sell = 0
    coin = 0
    profit = 0
    bank = 2000
    n = 50
    total_for_n = 0
    days_from_start = 0
    while (end != today):
        days.append(end)
        price = r.json()['bpi'][str(end)]
        day_to_day_bc_price.append(price)
        if days_from_start >= n:
            front_window_price = r.json()['bpi'][str(end - timedelta(days=n))]
            # print("yikes: "+str(front_window_price))
            average = total_for_n / n
            # print("this is n: "+str(n))
            total_for_n = total_for_n - front_window_price
            # print("running_average_n: "+str(total_for_n))
            # print("running average: "+str(average))
            if average > price:
                buy = buy + 1
                coin = coin + price / (price - buy_limit)
                profit = profit - buy_limit
                bank = bank - buy_limit
                day_to_day_bc_buy.append(end)
                buy_day_price.append(price)
                if profit > 0:
                    print("price: " + str(price))
                    print("buy profit: " + str(profit))
            elif average < price and coin > 0:
                sell = sell + 1
                coin = coin - price / (price - buy_limit)
                profit = profit + buy_limit
                bank = bank + buy_limit
                day_to_day_bc_sell.append(end)
                sell_day_price.append(price)
                if profit > 0:
                    print("price: " + str(price))
                    print("sell profit: " + str(profit))
        total_for_n = total_for_n + price
        end = end + timedelta(days=1)
        days_from_start = days_from_start + 1
    print("this is the profit using this algorithm: " + str(profit))
    print("coins bought: " + str(coin))
    print("coins value: " +
          str(coin * r.json()['bpi'][str(today - timedelta(days=1))]))
    print("total over all value: " +
          str(profit +
              (coin * r.json()['bpi'][str(today - timedelta(days=1))])))
    print("bank: " + str(bank))
    print("sell: " + str(sell))
    print("buy: " + str(buy))
    items = {
        "prices": day_to_day_bc_price,
        "days": days,
        "buy": day_to_day_bc_buy,
        "buy_day_prices": buy_day_price,
        "sell": day_to_day_bc_sell,
        "sell_day_prices": sell_day_price
    }
    return items
Exemplo n.º 5
0
def dlquotes(avKey, filePath, email, password, rh_watchlist):
    from datetime import datetime
    import os
    import sys
    import requests
    import robin_stocks as r
    import time
    from alpha_vantage.timeseries import TimeSeries
    ts = TimeSeries(key=avKey, output_format='pandas', indexing_type='date')
    processed_count = 0
    failed_symbols = []
    wlFile = filePath + 'Watchlist.csv'
    if os.path.exists(wlFile):
        os.remove(wlFile)
    f = open(wlFile, 'a')
    try:
        print("Logging into Robinhood to fetch watchlist symbols ... ")
        print("")
        rh_li_starttime = time.time()
        r.login(email, password)
        rh_li_endtime = time.time()
        rh_li_time = rh_li_endtime - rh_li_starttime
        print("Logged in. Time to complete login:"******"")
        print("Fetching watchlist symbols ...")
        print("")
        rh_wl_starttime = time.time()
        watchlist = r.get_watchlist_by_name(name=rh_watchlist, info=None)
        rh_wl_endtime = time.time()
        rh_wl_time = rh_wl_endtime - rh_wl_starttime
        print("Got the watchlist. Time to complete:", rh_wl_time)
        print("")
        watchlistDict = {}
        print("Putting watchlist symbols into file at", filePath+'Watchlist.csv ...')
        print("")
        for item in watchlist:
            url = item['instrument']
            r = requests.get(url)
            data_json = r.json()
            # print(str(data_json))  # print this to see more symbol info.
            watchlistDict[data_json['symbol']] = data_json['simple_name']
            print("Processing", str(watchlistDict[data_json['symbol']]))
            f.write(str(data_json['simple_name'])+",")
        f.close()
    except Exception as e:
        sys.exit(e)

    start_time = datetime.now()
    oldepoch = time.time()
    print("")
    print("Starting Quotes Download ...")
    print("Total number of symbols to update: ", len(watchlistDict))
    print("")
    total_symbols = len(watchlistDict)
    symbols_remaining = total_symbols
    processed_count_continuous = 0
    for _symbol, name in watchlistDict.items():
        try:
            rate_limit_begin_time = time.time()
            processed_count = processed_count+1
            processed_count_continuous = processed_count_continuous+1
            print(_symbol,": ",name)
            data, meta = ts.get_daily(_symbol,outputsize='full')
            fileName = _symbol + ".csv"
            fh = open(filePath + fileName, "w")
            fh.write( data.to_csv() )
            fh.close()
            symbols_remaining = symbols_remaining-1
            # Adjustments for AlphaVantage's Rate Limit, 5 symbols per minute
            if minute_passed(oldepoch) or processed_count==5:
                rate_limit_end_time = time.time()
                time_passed = rate_limit_end_time - rate_limit_begin_time
                pause_time = 60 - time_passed
                processed_count=0
                print("*** Pausing for ",pause_time," seconds.")
                print("*** ",symbols_remaining," symbols remain.")
                time_passed = datetime.now() - start_time
                print("*** Quotes Download has been running for ",time_passed)
                download_rate = time_passed / processed_count_continuous
                estimated_time_remaining = symbols_remaining * download_rate
                print("*** Estimated time remaining: ",estimated_time_remaining)
                est_end_time = datetime.now() + estimated_time_remaining
                print("*** Estimated end time: ",est_end_time)
                print("")
                time.sleep(pause_time)
                oldepoch = time.time()
        except Exception as e:
            print("Error on "+_symbol+": ", e)
            failed_symbols.append(_symbol)

    if len(failed_symbols) > 0:
        print("Initial download complete. Pausing 1 minute before downloading ", len(failed_symbols) ," failed symbols.")
        print("Failed symbols: "+str(failed_symbols))
        print("Please wait 1 minute ...")
        time.sleep(60)
        print("Now downloading failed symbols ...")
        name="Failed Symbol"
        symbols_remaining = len(failed_symbols)
        for _symbol in failed_symbols:
            try:
                rate_limit_begin_time = time.time()
                processed_count = processed_count+1
                processed_count_continuous = processed_count_continuous+1
                print(_symbol,": ",name)
                data, meta = ts.get_daily(_symbol,outputsize='full')
                fileName = _symbol + ".csv"
                fh = open(filePath + fileName, "w")
                fh.write( data.to_csv() )
                fh.close()
                symbols_remaining = symbols_remaining-1
                # Adjustments for AlphaVantage's Rate Limit, 5 symbols per minute
                if minute_passed(oldepoch) or processed_count==5:
                    rate_limit_end_time = time.time()
                    time_passed = rate_limit_end_time - rate_limit_begin_time
                    pause_time = 60 - time_passed
                    processed_count=0
                    print("*** Pausing for ",pause_time," seconds.")
                    print("*** ",symbols_remaining," symbols remain.")
                    time_passed = datetime.now() - start_time
                    print("*** This download has been running for ",time_passed)
                    download_rate = time_passed / processed_count_continuous
                    estimated_time_remaining = symbols_remaining * download_rate
                    print("*** Estimated time remaining: ",estimated_time_remaining)
                    est_end_time = datetime.now() + estimated_time_remaining
                    print("*** Estimated end time: ",est_end_time)
                    time.sleep(pause_time)
                    oldepoch = time.time()
            except Exception as e:
                print("***************************")
                print("Error on "+_symbol+": ",e)
                print(_symbol," quotes will not be downloaded on this run. Please try again.")
                print("***************************")

    else:
        end_time = datetime.now()
        print("**************************")
        print("")
        print("There were no failed symbols.")
        print("Time Elapsed: "+ str(end_time - start_time) )
        print("Completed at ",end_time)