Python Forum
Displaying Result from Data Frame from Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Displaying Result from Data Frame from Function
#1
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().
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Grouping in pandas/multi-index data frame Aleqsie 3 662 Jan-06-2024, 03:55 PM
Last Post: deanhystad
  Filtering Data Frame, with another value NewBiee 9 1,390 Aug-21-2023, 10:53 AM
Last Post: NewBiee
  Neural network and data analysis from clients survey result pthon3 2 1,894 Mar-17-2022, 02:21 AM
Last Post: jefsummers
  Exporting data frame to excel dyerlee91 0 1,626 Oct-05-2021, 11:34 AM
Last Post: dyerlee91
  Pandas Data frame column condition check based on length of the value aditi06 1 2,689 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Adding a new column to a Panda Data Frame rsherry8 2 2,123 Jun-06-2021, 06:49 PM
Last Post: jefsummers
  grouped data frame glitter 0 1,596 Feb-02-2021, 11:22 AM
Last Post: glitter
  how to filter data frame dynamically with the columns psahay 0 2,402 Aug-24-2020, 01:10 PM
Last Post: psahay
  Dropping Rows From A Data Frame Based On A Variable JoeDainton123 1 2,215 Aug-03-2020, 02:05 AM
Last Post: scidam
  How to shift data frame rows of specified column Mekala 0 1,896 Jul-21-2020, 02:42 PM
Last Post: Mekala

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020