【发布时间】:2016-05-05 11:35:22
【问题描述】:
from statistics import stdev
data = [line.rstrip('\n').split(',') for line in open('C:/Users/User/Downloads/documents-export-2016-05-04/Data.csv')]
dates = list(open('C:/Users/User/Downloads/documents-export-2016-05-04/Dates.csv').read().split('\n'))
stock_values = [int(x) for x in open('C:/Users/User/Downloads/documents-export-2016-05-04/stock_value.csv').read().split(',')]
companies = open('C:/Users/User/Downloads/documents-export-2016-05-04/companies.csv').read().split(',')
prices = dict(zip(companies, stock_values))
PRICE = 0
old_volatility = 0
new_volatility = 0
def get_change(values, invested):
sum_product = ([x * y for x, y in zip(values, invested)])
return(sum(sum_product) / sum(invested))
def get_volatility(invested):
changes = {}
for i, j in enumerate(list(reversed(dates))):
changes[j] = get_change(list(map(float, data[i])), invested.values())
vals = changes.values()
volatility = stdev(vals)
return volatility
def tuner(invested, company):
global PRICE
global old_volatility
temp_invested = invested.copy()
temp_invested[company] += 1
new_volatility = get_volatility(temp_invested)
new_price = PRICE + prices[company]
if new_volatility - old_volatility < -0.01 and new_price <= BUDGET:
old_volatility = new_volatility
PRICE = new_price
tuner(temp_invested, company)
else:
return invested
if __name__ == "__main__":
BUDGET = int(input())
invested = {}
for company in companies: invested[company] = 0
invested['A'] = 1
old_volatility = get_volatility(invested)
for company in companies:
if PRICE < BUDGET:
invested = tuner(invested, company)
else:
break
print("Price = ", PRICE)
print("Volatility = ", old_volatility)
由于上述代码中的某些原因,在 for 循环“for company in Companies”的 3 次迭代后,我收到一条错误消息,指出“'NoneType' 对象没有属性 'copy'”,指的是字典 'invested '。我不明白为什么经过几次迭代后,字典会突然被视为 NoneType。原始数据只是作为字符串列表读入,所以它们并不重要。任何帮助表示赞赏。谢谢。
【问题讨论】:
标签: python python-3.x dictionary nonetype stocks