【问题标题】:Function returning same values for supposedly different inputs函数为假定不同的输入返回相同的值
【发布时间】:2016-11-26 19:45:12
【问题描述】:

我正在使用 pyalgotrade 创建交易策略。我正在浏览一个代码列表(testlist)并将它们与我使用 get_score 函数获得的分数一起添加到字典(list_large{})中。我最新的问题是字典中的每个代码(list_large{})都获得了相同的分数。知道为什么吗?

代码:

from pyalgotrade import strategy
from pyalgotrade.tools import yahoofinance
import numpy as np
import pandas as pd
from collections import OrderedDict

from pyalgotrade.technical import ma
from talib import MA_Type
import talib

smaPeriod = 10
testlist = ['aapl','ddd','gg','z']

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed, 1000)
        self.__position = [] 
        self.__instrument = instrument
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def get_score(self,slope):
        MA_Score = self.__sma[-1] * slope
        return MA_Score

    def onBars(self, bars): 

        global bar 
        bar = bars[self.__instrument]

        slope = 8

        for instrument in bars.getInstruments():

            list_large = {}
            for tickers in testlist: #replace with real list when ready
                list_large.update({tickers : self.get_score(slope)}) 

            organized_list = OrderedDict(sorted(list_large.items(), key=lambda t: -t[1]))#organize the list from highest to lowest score

         print list_large


def run_strategy(inst):
    # Load the yahoo feed from the CSV file

    feed = yahoofinance.build_feed([inst],2015,2016, ".") # feed = yahoofinance.build_feed([inst],2015,2016, ".")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, inst)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()


def main():
    instruments = ['ddd','msft']
    for inst in instruments:
            run_strategy(inst)


if __name__ == '__main__':
        main()

【问题讨论】:

    标签: python function pyalgotrade


    【解决方案1】:

    查看onBars()函数的这段代码:

    slope = 8    # <---- value of slope = 8 
    
    for instrument in bars.getInstruments():
        list_large = {}
        for tickers in testlist: #replace with real list when ready
            list_large.update({tickers : self.get_score(slope)}) 
            #       Updating dict of each ticker based on ^
    

    每次调用self.get_score(slope),它都会返回相同的值,因此tickers 的所有值在dict 中保持相同的值

    我不知道你想如何处理slope 以及你想如何更新它的值。但是这个逻辑可以不用.update这样简化:

    list_large = {}
    for tickers in testlist: 
        list_large[tickers] = self.get_score(slope)
         #           ^ Update value of `tickers` key
    

    【讨论】:

    • 每次调用 self.get_score 它不应该返回相同的值。该函数采用 self.__sma[-1] 并将其乘以斜率...如果每个股票代码具有不同的移动平均线,那么放在字典中的值不应该不同吗?我有点迷茫……
    • @RageAgainstheMachine:你对self.__sma[-1] * slope的理解是什么?它从self.__sma 中获取最后一个条目,并将其与slope 相乘。不是每次都一样吗?
    • 我的印象是它将采用最近的 sma,但我认为我编写代码的方式是为列表中的每个股票代码采用最近的 sma。我将如何完成这项工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2021-07-09
    相关资源
    最近更新 更多