2016-05-04 89 views
-1
from numpy import std 
import csv 

data = [] 
with open('Data.csv') as file: 
    reader = csv.reader(file) 
    for column in zip(*reader): 
     data.append(column) 
dates = list(reversed(open('Dates.csv').read().split('\n'))) 
stock_value = [int(x) for x in open('stock_value.csv').read().split(',')] 
companies = open('companies.csv').read().split(',') 
stock_change = {} 
with open('Data.csv') as file: 
    reader = list(csv.reader(file)) 
    for i, j in enumerate(dates): 
     stock_change[j] = map(float, reader[i]) 
company_value = dict(zip(companies, stock_value)) 


def change(invested, date): 
    """Will return the change of invested stocks at the given date.""" 
    sum_product = sum([value[0] * value[1] * data for value, data 
        in zip(invested, stock_change[date])]) 
    _sum = sum([value[0] * value[1] for value in invested]) 
    return sum_product/_sum 


def total_change(invested): 
    """Will return the total change associated with an investment.""" 
    total_changes = [] 
    for date in dates: 
     total_changes.append(change(list(zip(stock_value, invested)), date)) 
    return total_changes 


def volatility(invested): 
    """Will return the std deviation from the total_change of the invested.""" 
    return std(total_change(invested), ddof=1) 


def tuner(invested): 
    """Will return a weight list.""" 
    weights = [] 
    for i in range(465): 
     temp = invested[:] 
     temp1 = temp[:] 
     print(stock_value) 
     while True: 
      temp[i] = temp[i] + 1 
      if volatility(temp) < volatility(temp1): 
       temp1 = temp[:] 
      else: 
       temp[i] = temp[i] - 1 
       break 
     weights.append(temp[i]) 
    return weights 

invested = [0] * 465 
invested[0] = 1 
print(tuner(invested)) 

的Data.csv文件包含881與這樣的數據線:值返回零一個操作之後

1.7529880478,2.8552887735,2.2606138577,1.7495626093,0.9274873524,0.6702840728,0.2543720191,2.1072796935,2.2385449458,2.2860610965,0.2590673575,... 

,其中每行對應於一個日期。 companies.csv是一個文件,其中包含由逗號分隔的465個條目,其中包含所有公司的名稱,stock_value.csv包含465個條目,並以逗號分隔,每個條目的值爲相同公司的股票的值索引。

在調諧器功能打印後我揮發的溫度,波動率爲temp1 = 0,然後在下一個迴路波動率爲temp = 0,波動率爲temp1。有誰知道我的價值爲什麼變成零?

+1

@AlexanderHuszagh對不起,我現在修好了。 –

+0

另外,對不起,這個例子中沒有日期。我相信stock_change和stock_value也不包括在內。沒有所有細節就很難修正一個例子。 如果這太多,請創建一個MVCE: https://stackoverflow.com/help/mcve –

+0

@AlexanderHuszagh這是足夠的細節還是我需要更多? –

回答

0

哦等等。我知道。對不起,我只是仔細查看了代碼。

你有這樣的(我改變了它,使其多一點清晰):

def change(vs): 
    product = sum([v[0] * v[1] * d for v, d in zip(vs, ds)]) 
    sums = sum([v[0] * v[1] for v in vs]) 
    return product/sums 

現在,利用基本的數學運算,我們得到的是:

(v1 * v2 * d)/(v1 * v2) 
(v1 * v2) * d/(v1 * v2) 
d 

所以,這個等式永遠等於:

def change(vs): 
    return sum(ds) 

如果您注意到,您的輸出不依賴於您的輸入,所以它是一個自變量,並因此返回一個常數值,清零所有的值。

這稍微過於簡化,因爲您確實通過了日期,然後抓住了庫存變化。但是由於傳遞了相同的日期數組,所以您將得到一個從total_change返回的常量值數組。