如何从列表中获取值,然后在基本数学方程式中使用它?

时间:2018-12-20 05:57:29

标签: python list multiplying

我正在尝试从api提供的列表中获取浮点值。我可以在打印时使它看起来像浮点值,但我认为它不是真实的数字,因为我无法在数学方程式中使用它。还有其他函数可以获取TrailTrigger和stopLoss,但我很高兴它们能够正常工作。我只是无法将lastTradePrice设为可以使用的浮动金额。

    # Call My last trade from Coinbase
def coinBaseMyLastTrade():
    global lastTradePrice
    global lastTradeSize
    global lastTradeFee
    global lastTradeSide
    global lastTradeSettled
    myLastTrade = requests.get(api_url + 'fills?product_id=BTC-USDC&limit=1', auth=auth)
    lastTradeList = myLastTrade.json()
    lastTradePrice = [float(lastTradeList_item['price']) for lastTradeList_item in lastTradeList]
    lastTradeSize = [float(lastTradeList_item['size']) for lastTradeList_item in lastTradeList]
    lastTradeFee = [float(lastTradeList_item['fee']) for lastTradeList_item in lastTradeList]
    lastTradeSide = [str(lastTradeList_item['side']) for lastTradeList_item in lastTradeList]
    lastTradeSettled = [lastTradeList_item['settled'] for lastTradeList_item in lastTradeList]
    print 'My Last Trade Price =',lastTradePrice
    print 'My Last Trade Size =',lastTradeSize
    print 'My Last Trade Fee =',lastTradeFee
    print 'My Last Trade Side =',lastTradeSide
    print 'My Last Trade Settled =',lastTradeSettled
    return

# Work out the value to use to trigger the trail loop
def calculateTrailTriggerValue():
    global triggerValue
    global stoplossValue
    if "buy" in lastTradeSide:
        triggerValue = lastTradePrice * ((100+trailTrigger)/100)
        stoplossValue = lastTradePrice * ((100-stoploss)/100)
    elif "sell" in lastTradeSide:
        triggerValue = lastTradePrice * ((100-trailTrigger)/100)
        stoplossValue = lastTradePrice * ((100+stoploss)/100)
    print 'Trail Trigger $=',triggerValue
    print 'Stop Loss $=',stoplossValue
    return

运行代码时出现错误

triggerValue = lastTradePrice * ((100-trailTrigger)/100)
TypeError: can't multiply sequence by non-int of type 'float'

这很奇怪,因为我在其他列表上使用了此代码,并且能够使用这些值,但是它与我需要帮助的代码不兼容

# Call 24hour stats
def coinBasePastDayStats():
    dayStats = requests.get('https://api.pro.coinbase.com/products/BTC-USDC/stats')
    dayHigh = float(dayStats.json()['high'])
    dayLow = float(dayStats.json()['low'])
    dayChange = dayHigh - dayLow
    global dayChangePercent
    dayChangePercent = (dayChange / dayHigh) * 100
    print 'Last 24hr High =', dayHigh
    print 'Last 24hr Low =', dayLow
    print 'Last 24hr Change =', dayChange
    print 'Last 24hr Change Percent =', {:.2f}".format(dayChangePercent),'%'
    return

如果有人可以帮助我获取列表值并将其用于基本数学方程式中,我将非常感激。 干杯

2 个答案:

答案 0 :(得分:1)

如果您想将整个列表相乘,建议使用numpy数组

import numpy as np
arr = np.array([ i for i in range(10)])
arr *= 2

答案 1 :(得分:1)

看起来您在正确的轨道上。但是正如其他人所说的那样,您正在对列表本身进行操作,而python不支持该操作。

如果不使用numpy,则必须遍历列表并依次对每个值进行操作。