Hello to All!
I have the below script I'm working on. It produce the error below, which seems to point on how to iterate over data frame. I tried various ways but still can't solve it. What am i missing or doing wrong? Any suggestion, help that enables me to resolve it would be appreciated. Thanks.
I have the below script I'm working on. It produce the error below, which seems to point on how to iterate over data frame. I tried various ways but still can't solve it. What am i missing or doing wrong? Any suggestion, help that enables me to resolve it would be appreciated. Thanks.
import pandas as pd import numpy as np from pandas_datareader import data start_date = '2018-01-01' end_date = '2019-12-31' data_values = data.DataReader('MSFT', 'yahoo', start_date, end_date) n_share = 25# Number of shares bought per batch isPositionOn = False Cash = 10000 direction = 0 portfolio_portion = .1 # Max proportion of portfolio bet on any trade #The role of this function is to oscillate between 1 and -1. #When it's 1, it signal to take position into a stock. def momentum(financial_data, nb_conseq_days): signals = pd.DataFrame(index=financial_data.index) signals['orders'] = 0 cons_day=0 prior_price=0 init=True for k in range(len(financial_data['Adj Close'])): price=financial_data['Adj Close'][k] if init: prior_price=price init=False elif price>prior_price: if cons_day<0: cons_day=0 cons_day+=1 elif price<prior_price: if cons_day>0: cons_day=0 cons_day-=1 if cons_day==nb_conseq_days: signals['orders'][k]=1 elif cons_day == -nb_conseq_days: signals['orders'][k]=-1 return signals def enter(position = None): direction = momentum(data_values, 5) if direction == 1: isPositionOn = True df = pd.DataFrame(position)#<---note this is the function's argument. for index, row in df.iterrows(): batches = np.floor(cash * portfolio_portion) // np.ceil(n_share * row["Adj Close"]) # Maximum number of batches of stocks invested in trade_value = batches * n_share * row["Adj Close"] # How much money is put on the line with each trade return trade_val if __name__ == "__main__": dF = pd.DataFrame(enter(data_values))#position = data_values for index, values in dF.item(): print(values)
Error:Traceback (most recent call last):
File "C:\Users\...\Desktop\trading_system.py", line 51, in <module>
dF = pd.DataFrame(enter(data_values))#position = data_values
File "C:\Users\14383\Desktop\trading_system.py", line 43, in enter
if direction == 1:
File "C:\Users\...\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\generic.py", line 1552, in __nonzero__
raise ValueError(
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().