Python Forum
Displaying Result from Data Frame from Function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Displaying Result from Data Frame from Function (/thread-25672.html)



Displaying Result from Data Frame from Function - eagle - Apr-07-2020

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.
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().



RE: Displaying Result from Data Frame from Function - eagle - Apr-08-2020

Hello everyone!
Still working on this problem. I manage to get an output: 4523.316192626953
based on some changes i made. Ideally, the function "enter" in my code will take a position when the function "momentum" is 1. That's where i struggle (and possibly in some other areas). These are the changes i made:
n_share = 50# Number of shares bought per batch
cash = 10000
portfolio_portion = .5  # Max proportion of portfolio bet on any trade
.
.
.
def enter(direction):
    position =  pd.DataFrame(index =data_values.index)
    position['Price'] = data_values['Adj Close']
    for index, row in position['Price'].iteritems():
        batches = np.floor(cash * portfolio_portion) // np.ceil(n_share * row) # Maximum number of batches of stocks invested in
        trade_value = batches * n_share * row # How much money is put on the line with each trade
        return trade_value
if __name__ == "__main__":
    result = (enter(momentum(data_values, 2)))#direction = momentum(data_values, 5)
    print(result)