简体   繁体   English

如何一次运行 3 个不同的 function

[英]how to run 3 different function at once

here's the requirement, I'm not so sure if I'm doing this right or wrong and I have code paste down below.这是要求,我不确定我这样做是对还是错,我在下面粘贴了代码。

so my question is I'm not so sure how to make this 3 function works together all at the once and when I tried to run it, this " file = open("/home/ubuntu/environment/hw5/" + tickers + ".txt") TypeError: must be str, not list" keep showing up and I don't know how to fixed it所以我的问题是我不太确定如何让这 3 个 function 一起工作,当我尝试运行它时,这个“file = open(”/home/ubuntu/environment/hw5/" + tickers + ".txt") TypeError: must be str, not list" 不断出现,我不知道如何解决

Create a function called meanReversionStrategy which takes a list called “prices” as an argument.创建一个名为 meanReversionStrategy 的 function,它将一个名为“价格”的列表作为参数。 The function runs a mean reversion strategy, and outputs to the console the buys and sells of the strategy (like you did in HW4). function 运行均值回归策略,并将策略的买卖输出到控制台(就像您在 HW4 中所做的那样)。 The function returns the profit and final returns percentage. function 返回利润和最终回报百分比。

-Create a function called simpleMovingAverageStrategy which takes a list called “prices” as an argument. - 创建一个名为 simpleMovingAverageStrategy 的 function,它将一个名为“价格”的列表作为参数。 The function runs a Simple Moving Average strategy, and outputs to the console the buys and sells of the strategy. function 运行简单移动平均策略,并将策略的买入和卖出输出到控制台。 The function returns the profit and final returns percentage. function 返回利润和最终回报百分比。

-Create a function called saveResults which takes a dictionary as an argument. - 创建一个名为 saveResults 的 function,它将字典作为参数。 Save the dictionary to a json file called “results.json”.将字典保存到名为“results.json”的 json 文件中。

the basic logic, explained above, will look like this上面解释的基本逻辑如下所示

this logic is not complete, but you are allowed to copy/paste and start with this此逻辑不完整,但您可以复制/粘贴并以此开始

define function meanReversionStrategy定义 function meanReversionStrategy

run strategy and output buys/sells, final profit, and final percentage returns运行策略和 output 买入/卖出、最终利润和最终百分比回报

return profit and returns回报利润和回报

define function simpleMovingAverageStrategy定义 function simpleMovingAverageStrategy

run strategy and output buys/sells, final profit, and final percentage returns运行策略和 output 买入/卖出、最终利润和最终百分比回报

return profit and returns回报利润和回报

define function saveResults定义 function 保存结果

create list to store 10 tickers创建列表以存储 10 个代码

create dictionary called results to store prices, profits and return percentages创建名为 results 的字典来存储价格、利润和回报百分比

loop through the list of tickers遍历代码列表

for ticker in tickers:对于股票代码:

-load prices from a file.txt, and store them in the results dictionary with the - 从 file.txt 加载价格,并将它们存储在结果字典中

key “_prices”关键“_prices”

-call meanReversionStrategy(prices) and store the profit and returns in the results -调用 meanReversionStrategy(prices) 并将利润和回报存储在结果中

dictionary with the keys “_mr_profit” and “_mr_returns”带有键“_mr_profit”和“_mr_returns”的字典

-call simpleMovingAverageStrategy(prices) and store the profit and returns in the - 调用 simpleMovingAverageStrategy(prices) 并将利润和收益存储在

results dictionary with the keys “_sma_profit” and “_sma_profit”带有键“_sma_profit”和“_sma_profit”的结果字典

with the keys “ticker_mr_profit” and “ticker_mr_returns”使用键“ticker_mr_profit”和“ticker_mr_returns”

call saveResults(results) and save the results dictionary to a file called results.json调用 saveResults(results) 并将结果字典保存到名为 results.json 的文件中

Create a function called meanReversionStrategy which takes a list called “prices” as an argument.创建一个名为 meanReversionStrategy 的 function,它将一个名为“价格”的列表作为参数。 The function runs a mean reversion strategy, and outputs to the console the buys and sells of the strategy (like you did in HW4). function 运行均值回归策略,并将策略的买卖输出到控制台(就像您在 HW4 中所做的那样)。 The function returns the profit and final returns percentage. function 返回利润和最终回报百分比。

-Create a function called simpleMovingAverageStrategy which takes a list called “prices” as an argument. - 创建一个名为 simpleMovingAverageStrategy 的 function,它将一个名为“价格”的列表作为参数。 The function runs a Simple Moving Average strategy, and outputs to the console the buys and sells of the strategy. function 运行简单移动平均策略,并将策略的买入和卖出输出到控制台。 The function returns the profit and final returns percentage. function 返回利润和最终回报百分比。

-Create a function called saveResults which takes a dictionary as an argument. - 创建一个名为 saveResults 的 function,它将字典作为参数。 Save the dictionary to a json file called “results.json”.将字典保存到名为“results.json”的 json 文件中。

the basic logic, explained above, will look like this上面解释的基本逻辑如下所示

this logic is not complete, but you are allowed to copy/paste and start with this此逻辑不完整,但您可以复制/粘贴并以此开始

define function meanReversionStrategy定义 function meanReversionStrategy

run strategy and output buys/sells, final profit, and final percentage returns运行策略和 output 买入/卖出、最终利润和最终百分比回报

return profit and returns回报利润和回报

define function simpleMovingAverageStrategy定义 function simpleMovingAverageStrategy

run strategy and output buys/sells, final profit, and final percentage returns运行策略和 output 买入/卖出、最终利润和最终百分比回报

return profit and returns回报利润和回报

define function saveResults定义 function 保存结果

create list to store 10 tickers创建列表以存储 10 个代码

create dictionary called results to store prices, profits and return percentages创建名为 results 的字典来存储价格、利润和回报百分比

loop through the list of tickers遍历代码列表

for ticker in tickers:对于股票代码:

-load prices from a file.txt, and store them in the results dictionary with the - 从 file.txt 加载价格,并将它们存储在结果字典中

key “_prices”关键“_prices”

-call meanReversionStrategy(prices) and store the profit and returns in the results -调用 meanReversionStrategy(prices) 并将利润和回报存储在结果中

dictionary with the keys “_mr_profit” and “_mr_returns”带有键“_mr_profit”和“_mr_returns”的字典

-call simpleMovingAverageStrategy(prices) and store the profit and returns in the - 调用 simpleMovingAverageStrategy(prices) 并将利润和收益存储在

results dictionary with the keys “_sma_profit” and “_sma_profit”带有键“_sma_profit”和“_sma_profit”的结果字典

with the keys “ticker_mr_profit” and “ticker_mr_returns”使用键“ticker_mr_profit”和“ticker_mr_returns”

call saveResults(results) and save the results dictionary to a file called results.json调用 saveResults(results) 并将结果字典保存到名为 results.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") )```

You can call the function you want inside a function with parameters.您可以在带有参数的 function 中调用您想要的 function。

eg: def average (price1, price2): *the parameters avg=(price1+price2)/2 return avg eg: def average (price1, price2): *参数avg=(price1+price2)/2 return avg

def simpleMovingAverageStrategy(prices): *your code average(price1,price2) def simpleMovingAverageStrategy(prices): *你的代码 average(price1,price2)

*Pardon me my coding is a bit rusty *请原谅我的编码有点生疏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM