【问题标题】:how to do loop over the tickers and save result on the dictionary如何循环代码并将结果保存在字典中
【发布时间】:2022-01-11 04:48:30
【问题描述】:

我不太确定如何做最后一部分,即字典部分和股票代码部分,还有 在 “”file = open("/home/ubuntu/environment/hw5/" + tickers + ".txt")""" 此行一直显示

TypeError: 必须是 str,而不是 list

关于如何修复这些问题或使代码正常工作的任何建议?

这是我的代码


import json


def meanReversionStrategy(prices):
    
    total_profit = 0
    first_buy = None
    buy = 0
    for i in range(len(prices)):  
        
        
        if i >= 5: 
            current_price = prices[i]  
            moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] +prices[i-5]) / 5
        
            if current_price < moving_average * 0.95 and buy == 0:
                buy = current_price
                print("buy at:  ",round (current_price,2))  
                if first_buy is None:
                    first_buy = buy
                                
    
            elif current_price > moving_average * 1.05 and buy != 0:    
                
                print("sell at: ", round(current_price,2))
                print("trade profit:  ", round(current_price - buy,2))
                total_profit = current_price - buy
                buy = 0
            
            
    final_profit_percentage = ( total_profit / first_buy ) * 100 
    print("First buy: " ,  round(first_buy,2))
    print("Total profit: " , round(total_profit, 2))
    print("Percentage return: ", round(final_profit_percentage, 2),"%")  

def simpleMovingAverageStrategy(prices):
    i = 0
    buy = 0
    total_profit = 0
    first_buy = 0
    for p in prices:
        if i >= 5: 
            moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] + 
    prices[i-5]) / 5
            
            #simple moving average logic, not mean
            if p > moving_average and buy == 0: #buy
                print("buying at: ", p)
                buy = p
                if first_buy == 0:
                    first_buy = p
            elif p < moving_average and buy != 0: #sell
                print("selling at: ", p)
                print("trade profit: ", p - buy)
                total_profit += p - buy
                buy = 0
        i += 1
        
    final_percentage = (total_profit / first_buy) * 100
    print("first buy: ", first_buy)
    print("total profit: ", total_profit)
    print("final percentage: ", final_percentage, "%")
    
    return total_profit, final_percentage
        
        
tickers = ["AAPL1" , "ADBE" , "BA", "CMCSA", "CSCO", "CVS", "GOOG", "TLSYY","TM"]

file = open("/home/ubuntu/environment/hw5/" + tickers + ".txt")
lines = file.readlines()
# print(lines)
prices = []
for line in lines:
    prices.append(float(line))
    
    
profit, returns = simpleMovingAverageStrategy(prices)

results = {}
results["AAPL1_profit"] =profit
results["AAPL1_returns"] = returns

json.dump(results, open("/home/ubuntu/environment/hw5/results.json", "w") )

编码要求

-创建一个名为 meanReversionStrategy 的函数,它接受一个名为“prices”的列表作为参数。该函数运行均值回归策略,并将策略的买卖输出到控制台(就像您在 HW4 中所做的那样)。函数返回利润和最终收益百分比。

-创建一个名为 simpleMovingAverageStrategy 的函数,该函数将一个名为“价格”的列表作为参数。该函数运行一个简单移动平均线策略,并将策略的买入和卖出输出到控制台。函数返回利润和最终收益百分比。

-创建一个名为 saveResults 的函数,该函数将字典作为参数。将字典保存到名为“results.json”的 json 文件中。

遍历代码列表

在代码中的代码:

-load prices from a file <ticker>.txt, and store them in the results dictionary with the
key “<ticker>_prices”
-call meanReversionStrategy(prices) and store the profit and returns in the results
dictionary with the keys “<ticker>_mr_profit” and “<ticker>_mr_returns”
-call simpleMovingAverageStrategy(prices) and store the profit and returns in the
results dictionary with the keys “<ticker>_sma_profit” and “<ticker>_sma_profit”
with the keys “ticker_mr_profit” and “ticker_mr_returns”

调用 saveResults(results) 并将结果字典保存到名为 results.json 的文件中

【问题讨论】:

  • 关于如何改进这个问题的一些建议: - 提供一个有意义的标题,无需阅读整个问题即可理解 - 将您的问题一次限制为一个问题。不要问解决你完整的家庭作业,它可能会冒犯人们,并且不是stackoverflow的问答主题。与此相关:尝试提供一个最小的示例和问题。
  • 知道了!非常感谢!

标签: python json dictionary


【解决方案1】:

欢迎!

由于这是一个家庭作业问题,我不会为你解决它,但这里是我给你的建议:

tickers 是一个数组,正如您的作业描述所述,您必须“遍历代码列表”和 open 每个。那么你如何遍历tickers

并反思错误。你认为"/home/ubuntu/environment/hw5/" + tickers + ".txt" 的结果应该是什么?

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多