Индекс присвоения скалярной переменной в Python не ясен из-за ошибки с плавающей запятой - PullRequest
0 голосов
/ 02 августа 2020

Я новичок в Python и хотел вручную кодировать индикатор VWAP Stock. Я загружаю JSON поверх net, а затем пытаюсь создать необходимые массивы заполнителей. Не уверен, что не так с массивом totalVolume.

Я объявил totalVolume как массив с плавающей запятой. Тем не менее я получаю скалярную ошибку в строке 81. totalVolume [i] = volume [i] + totalVolume [i-1] IndexError: недопустимый индекс для скалярной переменной.

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()

1 Ответ

1 голос
/ 02 августа 2020
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]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...