0

I am new to Python and wanted to code the VWAP Stock indicator by hand. I download a JSON over the net and then try to create the necessary placeholder arrays. Not sure what goes wrong with the totalVolume Array.

I have declared the totalVolume as Array of float. Still I get scalar error on line 81. totalVolume[i] = volume[i] + totalVolume[i-1] IndexError: invalid index to scalar variable.

import requests
import csv
import os
import threading
import time
import talib
import numpy
import json
from pyalgotrade.technical import vwap

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter, url):
    # Stock URL https://www.programcreek.com/python/?project_name=doncat99%2FStockRecommendSystem#
    #https://www.quantopian.com/posts/sample-talib-macd
    #https://www.daytrading.com/vwap
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
      print_time(self.name, 5, self.counter)
      print "Exiting " + self.name

def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1

def clean(url): 
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "Referer": "http://example.com"}
    r = requests.get(url, headers=headers, timeout=50)
    #print(r.content)
    data  = json.loads(r.content)
    #print(data['t'])
    close = data['c']
    closeArray = numpy.array(close)
    #print(close)
    RSI = talib.RSI(closeArray, timeperiod=14)
    print(RSI[-1])
    macd, signal, hist = talib.MACD(closeArray)
    msdiff = macd[-1] - signal[-1]
    print(msdiff)
    getVWAP(data)

def getVWAP(data):
    open = numpy.array(data['o'])
    low = numpy.array(data['l'])
    high = numpy.array(data['h'])
    close = numpy.array(data['c'])
    volume = numpy.array(data['v'])
    print(len(open))
    print(len(low))
    print(len(high))
    print(len(close))
    print(len(volume))
    typicalPrice = [float]*len(open)
    VP = [float]*len(open)
    totalVP = [float]*len(open)
    VWAP = [float]*len(open)
    totalVolume = numpy.zeros(len(open))

    for i in range(0, len(open)):
        totalVolume[i] = 0
        print("A"),

    for i in range(0, len(open)):    
         typicalPrice[i] = (open[i] + high[i] + low[i])/3.0
         VP[i] = volume[i] * typicalPrice[i]
         if i==0:
            totalVP[0] = VP[0]
            totalVolume = volume[0]
            VWAP[0] = typicalPrice[0]
         else:
            totalVP[i] = VP[i-1] + volume[i]
            totalVolume[i] = volume[i] + totalVolume[i-1]
            VWAP[i] = (totalVP[i])/totalVolume[i]
         print("@"),



    print("Abhi3")


# Create new threads
thread1 = myThread(1, "Thread-1", 1, "")
thread2 = myThread(2, "Thread-2", 2, "")

# Start new Threads
#thread1.start()
#thread2.start()
url1 = "https://tvc4.forexpros.com/b08251ec88a94408cab3716001818cc2/1596166039/56/56/23/history?symbol=18270&resolution=5&from=1595872548&to=1596304608"
url2 = "https://tvc4.forexpros.com/b08251ec88a94408cab3716001818cc2/1596166039/56/56/23/history?symbol=18270&resolution=5&from=1595872548&to=1596304608"
clean(url1)
clean(url2)
print talib.get_functions()
11
  • It looks like totalVolume = volume[0] is setting totalVolume to a scalar quantity, after which indexing will fail. Commented Aug 2, 2020 at 15:22
  • [float]*len(open) what did you expect to get here? Commented Aug 2, 2020 at 15:28
  • I expected declaring a float array of size 300 Commented Aug 2, 2020 at 15:29
  • 3
    Not trying to be mean, but... you have 20.7k reputation and don't know how to format code, how to debug code, or how to post a minimal reproducible example? Commented Aug 2, 2020 at 15:29
  • 1
    Did you read stackoverflow.com/help/minimal-reproducible-example ? Your example is anything but minimal. Commented Aug 2, 2020 at 15:40

1 Answer 1

1
def getVWAP(data):
    # if data is a pandas dataframe, just use data['o'].values instead
    open = numpy.array(data['o'])
    low = numpy.array(data['l'])
    high = numpy.array(data['h'])
    close = numpy.array(data['c'])
    volume = numpy.array(data['v'])

    # it's better to use logging.debug for debug output
    print(len(open), len(low), len(high), len(close), len(volume))

    # default dtype is float, but you can be more explicit
    typicalPrice = np.zeros(len(open), dtype=float)
    # another way to improve this is to use zeros_like,
    # which will generalize beyond 1D arrays
    VP = np.zeros_like(open)
    # but actually, we don't need to initialize these arrays at all
    # because we calculate them directly (see below)    

    # numpy arrays can be added/subtracted/... directly
    # it is actually quite a bit faster
    typicalPrice = (open + high + low)/3
    VP = volume * typicalPrice
    totalVolume = np.cumsum(volume)
    totalVP = np.cumsum(VP)
    VWAP = totalVP/totalVolume
    
    # this line is different. A typo?
    VWAP[0] = typicalPrice[0]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Marat. Let me try. I think with my code it is obvious I don't know enough of NumPy. The last line is not a typo. The 0th element doesn't require any compute so I simply reassigned it to typicalPrice.
It looks ok from Python perspective. This time it's more about numpy arrays, and there is definitely a learning curve
Thanks @Marat. Your code actually worked for me. I appreciate your help. How quickly you converted this code is also really impressive. Cheers !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.