Bottom Page

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

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Pandas data frame creation from Kafka Topic vboppa 0 47 Jul-01-2020, 04:23 PM
Last Post: vboppa
  Filter rows by multiple text conditions in another data frame i.e contains strings an Pan 0 271 Jun-09-2020, 06:05 AM
Last Post: Pan
  add formatted column to pandas data frame alkaline3 0 226 Mar-22-2020, 06:44 PM
Last Post: alkaline3
  reformatting data frame tkirkland 0 167 Mar-18-2020, 02:17 PM
Last Post: tkirkland
  How to modify data frame row value SriRajesh 0 200 Feb-12-2020, 05:46 PM
Last Post: SriRajesh
  Handling escape charters while converting data frame to JSON RahulShukla 0 298 Nov-11-2019, 11:22 AM
Last Post: RahulShukla
  Loop pandas data frame by position ? Johnse 1 539 Sep-06-2019, 12:26 AM
Last Post: scidam
  pandas data frame dervast 1 445 Aug-28-2019, 12:40 PM
Last Post: ThomasL
  Insert Pandas Data Frame into Teradata DB kylenater 0 2,050 Jul-19-2019, 04:53 PM
Last Post: kylenater
  Creating new rows and adding them to empty data frame kapilan15 0 506 May-31-2019, 10:19 AM
Last Post: kapilan15

Forum Jump:


Users browsing this thread: 1 Guest(s)