Advertisement
asd1q23

An example of a typical strategy

May 13th, 2014
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.50 KB | None | 0 0
  1.     #@autojit
  2.     def MakeTrade(self, dd, data, data_i, trade_quantity, trade_price, tradeRecordColumn, the_stop_price):
  3.         trade_quantity = int(trade_quantity)    #make sure this is an int
  4.         if trade_quantity == 0:
  5.             return
  6.         if (self.cashInHand < 0.0):
  7.             return
  8.         if (self.numSharesHeld < 0) and (trade_quantity < 0):
  9.             return
  10.         if (self.numSharesHeld > 0) and (trade_quantity > 0):
  11.             return
  12.  
  13.         self.someSharesTraded = True
  14.  
  15.         store_it = False
  16.         if data is None:
  17.             data = dd.loc[data_i].copy()
  18.             store_it = True             ## maybe this should be a named parameter
  19.  
  20.  
  21.         if trade_quantity != 0:        #was self.NumSharesTraded != 0:
  22.  
  23.             cashInHand_Before = self.cashInHand
  24.             numSharesHeld_Before = self.numSharesHeld
  25.             data['NumSharesHeld']  = self.numSharesHeld               = self.numSharesHeld + trade_quantity
  26.             data['NumSharesTraded']   = self.NumSharesTraded          = self.NumSharesTraded + trade_quantity;
  27.             data['ValueSharesTraded'] = self.ValueSharesTraded        = self.ValueSharesTraded + (trade_quantity * trade_price)
  28.  
  29.             if (tradeRecordColumn is not None):
  30.                 data[tradeRecordColumn] = trade_price
  31.  
  32.             if numSharesHeld_Before == 0:
  33.                 cashInHand_After = round(cashInHand_Before - abs(trade_quantity * trade_price), 2)  # any trade costs money
  34.                 self.trade_open_price = trade_price
  35.  
  36.                 if the_stop_price is not None:
  37.                     if trade_quantity > 0:
  38.                         self.long_stop_price = the_stop_price
  39.                     else:
  40.                         self.short_stop_price = the_stop_price
  41.  
  42.             elif numSharesHeld_Before > 0:
  43.                 if trade_quantity > 0:
  44.                     print "trying to buy on top of a long position"
  45.                 else:
  46.                     t1 = abs(trade_quantity) * self.trade_open_price                #original cost of shares to trade
  47.                     t2 = (self.trade_open_price - trade_price ) * trade_quantity    #profit from trade
  48.                     ValueTradeChange =  t1 + t2
  49.                     cashInHand_After = round(cashInHand_Before + ValueTradeChange, 2)
  50.  
  51.  
  52.             elif numSharesHeld_Before < 0:
  53.                 if trade_quantity > 0:
  54.                     t1 = abs(trade_quantity) * self.trade_open_price                #original cost of shares to trade
  55.                     t2 = (self.trade_open_price - trade_price ) * trade_quantity    #profit from trade
  56.                     ValueTradeChange =  t1 + t2
  57.                     cashInHand_After = round(cashInHand_Before + ValueTradeChange, 2)
  58.                 else:
  59.                     print "trying to sell when already short"
  60.             else:
  61.                 print "madness"
  62.  
  63.  
  64.             if debug:
  65.                 print str(data_i) + "\tMakeTrade " + str(tradeRecordColumn) + "\t" + str(trade_quantity) + " shares @\t" + str(trade_price) + " [ cashBefore =\t" + str(cashInHand_Before) + \
  66.                         " sharesBefore =\t" + str(numSharesHeld_Before) + " ]\t[ cashAfter =\t" + str(cashInHand_After) + "\t sharesAfter =\t" + str (self.numSharesHeld) + " ]"
  67.  
  68.             data['CashInHand']         = self.cashInHand        = cashInHand_After
  69.  
  70.             if self.numSharesHeld == 0:
  71.                 data['CashInvested']           = 0
  72.                 self.trade_open_price               = np.NaN    ##   shouldnt ever be read.
  73.             else:
  74.                 data['CashInvested']           = 10000
  75.  
  76.             if store_it == True:
  77.                 dd.loc[data_i] = data
  78.  
  79.  
  80.  
  81.     #@autojit
  82.     def Run_OnSymbol(self,
  83.                             df,
  84.                             LS_ema,
  85.                             LS_width,
  86.                             TP1_ema,
  87.                             TP1_pct,
  88.                             TP1_width,
  89.                             TP1_profitWidth,
  90.                             target_width,
  91.                             stop_ema,
  92.                             stop_ema_width,
  93.                             stop_window,
  94.                             ):
  95.  
  96.         dataNeeded = max(125, LS_ema, TP1_ema, 200*7)
  97.         if ((df.shape[0]-5) <= dataNeeded):
  98.             for i in xrange (20):
  99.                 print "SHAPE TOO SMALL - SKIPPING"
  100.             print df.shape[0]
  101.             print "min = " + str(min(125, LS_ema, TP1_ema))
  102.             print "LS_ema = " + str(LS_ema)
  103.             print "TP1_ema = " + str(TP1_ema)
  104.             return None
  105.  
  106. #        df["Active"][:dataNeeded] = 0
  107.  
  108.  
  109.         df["LS_EMA"] = pd.ewma(df.Close, min_periods=LS_ema-1, span = LS_ema).bfill()
  110.         df["TP1_EMA"] = pd.ewma(df.Close, min_periods=TP1_ema-1, span = TP1_ema).bfill()
  111.         df["Stop_EMA"] = pd.ewma(df.Close, min_periods=stop_ema-1, span = stop_ema).bfill()
  112.  
  113.         df["H2"] = pd.rolling_max(df["High"], 2, min_periods = 2)
  114.         df["L2"] = pd.rolling_min(df["Low"], 2, min_periods = 2)
  115.         df["HL2"] = (df["H2"] + df["L2"]) / 2.0 #(MAXH2 + MINL2)/2
  116.  
  117.         XAVGH125 = pd.ewma(df.High, min_periods=125-1, span = 125).bfill()
  118.         XAVGL125 = pd.ewma(df.Low,  min_periods=125-1, span = 125).bfill()
  119.         df["ChanWidth"] = XAVGH125 - XAVGL125
  120.  
  121.  
  122.  
  123.         #Create Long Short Ema chan
  124.         LS_EMA_width = df["ChanWidth"] * LS_width
  125.         df["LS_EMA_ChanTop"] = df["LS_EMA"] + LS_EMA_width
  126.         df["LS_EMA_ChanBot"] = df["LS_EMA"] - LS_EMA_width
  127.         #Crossing events against Long short EMA channel
  128.         df["HL2_XUp_LS_ChanTop"]   = (np.sign(df["HL2"] - df["LS_EMA_ChanTop"]).diff().fillna(0.0)).gt(0.0)
  129.         df["HL2_XDn_LS_ChanBot"]   = (np.sign(df["HL2"] - df["LS_EMA_ChanBot"]).diff().fillna(0.0)).lt(0.0)
  130.  
  131.  
  132.  
  133.         #Create Take profit Ema chan
  134.         TP1_EMA_width = df["ChanWidth"] * TP1_width     # normally 0.0 width
  135.         df["TP1_EMA_ChanTop"] = df["TP1_EMA"] + TP1_EMA_width
  136.         df["TP1_EMA_ChanBot"] = df["TP1_EMA"] - TP1_EMA_width
  137.         #Crossing events against Take profit EMA chan
  138.         df["HL2_XDn_TP1_ChanBot"] = (np.sign(df["HL2"] - df["TP1_EMA_ChanBot"]).diff().fillna(0.0)).lt(0.0) # HL2 XDn ChanBot          ##why bother with fillna ?
  139.         df["HL2_XUp_TP1_ChanTop"] = (np.sign(df["HL2"] - df["TP1_EMA_ChanTop"]).diff().fillna(0.0)).gt(0.0) # HL2 XUp ChanTop
  140.         #df["H2_XUp_TP1_ChanTop"] = (np.sign(df["HL2"] - df["TP1_EMA_ChanTop"]).diff().fillna(0.0)).gt(0.0)
  141.         #df["HL2_XDn_TP1_ChanBot"] = (np.sign(df["HL2"] - df["TP1_EMA_ChanBot"]).diff().fillna(0.0)).lt(0.0)
  142.  
  143.  
  144.  
  145.         #Create Stop Ema chan
  146.         Stop_EMA_width = df["ChanWidth"] * stop_ema_width     # normally 0.0 width
  147.         df["Stop_EMA_ChanTop"] = df["Stop_EMA"] + Stop_EMA_width
  148.         df["Stop_EMA_ChanBot"] = df["Stop_EMA"] - Stop_EMA_width
  149.         #Crossing events against stop EMA chan
  150.         df["HL2_XDn_Stop_ChanBot"] = (np.sign(df["HL2"] - df["Stop_EMA_ChanBot"]).diff().fillna(0.0)).lt(0.0) # HL2 XDn ChanBot          ##why bother with fillna ?
  151.         df["HL2_XUp_Stop_ChanTop"] = (np.sign(df["HL2"] - df["Stop_EMA_ChanTop"]).diff().fillna(0.0)).gt(0.0) # HL2 XUp ChanTop
  152.  
  153.  
  154.         #Create target Ema chan
  155.         Target_EMA_width = df["ChanWidth"] * target_width
  156.         df["Target_EMA_ChanTop"] = df["LS_EMA"] + Target_EMA_width         ## offset from the LS_EMA
  157.         df["Target_EMA_ChanBot"] = df["LS_EMA"] - Target_EMA_width
  158.         #Crossing events against profit target defined as a channel with width from an ema.
  159.         df["HL2_XDn_Target_ChanBot"] = (np.sign(df["HL2"] - df["Stop_EMA_ChanBot"]).diff().fillna(0.0)).lt(0.0) # HL2 XDn ChanBot          ##why bother with fillna ?
  160.         df["HL2_XUp_Target_ChanTop"] = (np.sign(df["HL2"] - df["Stop_EMA_ChanTop"]).diff().fillna(0.0)).gt(0.0) # HL2 XUp ChanTop
  161.  
  162.  
  163.  
  164.         # This doesnt do widths
  165.         #cross_TP1_ema                   = np.sign(df["HL2"] - df["TP1_EMA"]).diff().fillna(0.0)           ## -2, 0 or +1 .... Most of the time this is zero.. also dont backfill this
  166.         #df["HL2_XUp_TP1"]               = cross_TP1_ema.gt(0.0)
  167.         #df["HL2_XDn_TP1"]               = cross_TP1_ema.lt(0.0)
  168.  
  169.  
  170.         #df["YYYDayHigh"] = pd.rolling_max(df["High"].shift(1), new_high_periods, min_periods = new_high_periods).bfill()
  171.         #df["YYYDayLow"]  = pd.rolling_min(df["Low"].shift(1), new_low_periods, min_periods = new_low_periods).bfill()
  172.         df["LongRollingStopPrice"]  = pd.rolling_min(df["Low"].shift(1), stop_window, min_periods = stop_window).bfill()
  173.         df["ShortRollingStopPrice"] = pd.rolling_max(df["High"].shift(1), stop_window, min_periods = stop_window).bfill()
  174.  
  175.     #    df["SignAbvBel"]                = np.sign(df["Close"] - df["EMA"]).bfill()
  176.         #df["DaysBelow"]                   = (df["Close"].lt( df["EMA"])).bfill()
  177.         #df["DaysAbove"]                   = (df["Close"].gt( df["EMA"])).bfill()
  178.  
  179.         #df["RollingSumDaysBelow"]      = pd.rolling_sum(df["DaysBelow"], window = count_days_below_window, min_periods = count_days_below_window).bfill()       ##fillna instead ?
  180.         #df["RollingSumDaysAbove"]      = pd.rolling_sum(df["DaysAbove"], window = count_days_below_window, min_periods = count_days_below_window).bfill()       ## this might not be necessary
  181.         #df["RollingSumBelowEnough"]    = df["RollingSumDaysBelow"].gt(excess_days_AbvBel_threshold) #| df["RollingSumDaysBelow"].lt(count_days_below_window - excess_days_AbvBel_threshold)
  182.         #df["RollingSumAboveEnough"]    = df["RollingSumDaysAbove"].gt(excess_days_AbvBel_threshold) #| df["RollingSumDaysAbove"].lt(count_days_below_window - excess_days_AbvBel_threshold)
  183.  
  184.         #df["HighCrossedAboveYYYDayHighBool"]    = (np.sign(df["High"] - df["YYYDayHigh"]).diff().fillna(0.0)).gt(0.0)
  185.         #df["LowCrossedBelowYYYDayLowBool"]      = (np.sign(df["Low"]  - df["YYYDayLow"]) .diff().fillna(0.0)).lt(0.0)
  186.  
  187.         """Bias mode... Only go long if  "EMA2 > EMA200".... or more complex like "EMA2 > EMA10 && EMA10 > EMA20 && EMA20 > EMA40 && EMA 40 > EMA200"
  188.                        Only go short if "EMA2 < EMA200".... or more complex like "EMA2 > EMA10 && EMA10 > EMA20 && EMA20 > EMA40 && EMA 40 > EMA200"
  189.        """
  190.         df["50DayEma"]  = pd.ewma(df.Close, min_periods= ( 50*7)-1, span =  50*7).bfill()
  191.         df["100DayEma"] = pd.ewma(df.Close, min_periods= (100*7)-1, span = 100*7).bfill()
  192.         df["200DayEma"] = pd.ewma(df.Close, min_periods= (200*7)-1, span = 200*7).bfill()
  193.  
  194.         df["LongBias"]  = (df["HL2"] > df["50DayEma"]) & (df["50DayEma"] > df["100DayEma"]) & (df["100DayEma"] > df["200DayEma"])
  195.         df["ShortBias"] = (df["HL2"] < df["50DayEma"]) & (df["50DayEma"] < df["100DayEma"]) & (df["100DayEma"] < df["200DayEma"])
  196.         #What about SPY above/below 100/200 day (only if stock correlates with SPY movements?)
  197.  
  198.         df["ActiveDiff"]                = df["Active"].diff().fillna(0)
  199.         #df["GoLong"]                    = df["HighCrossedAboveYYYDayHighBool"] | (df["CrossUpEma"] & df["RollingSumBelowEnough"])
  200.         #df["GoShort"]                   = df["LowCrossedBelowYYYDayLowBool"]   | (df["CrossDnEma"] & df["RollingSumAboveEnough"])
  201. #alt        df["GoLong"]                    = df["HL2_XUp_LS_ChanTop"] & df["Active"]
  202. #alt        df["GoShort"]                   = df["HL2_XDn_LS_ChanBot"] & df["Active"]
  203.         df["GoLong"]                    = df["HL2_XDn_LS_ChanBot"] & df["Active"]
  204.         df["GoShort"]                   = df["HL2_XUp_LS_ChanTop"] & df["Active"]
  205.  
  206.  
  207.         df["LTP1"]                       = df["HL2_XDn_TP1_ChanBot"] & df["Active"]
  208.         df["STP1"]                       = df["HL2_XUp_TP1_ChanTop"] & df["Active"]
  209.         df["LongStopEMA_Hit"]            = df["HL2_XDn_Stop_ChanBot"] & df["Active"]
  210.         df["ShortStopEMA_Hit"]           = df["HL2_XUp_Stop_ChanTop"] & df["Active"]
  211.         df["LongTargetEMA_Hit"]          = df["HL2_XUp_Target_ChanTop"] & df["Active"]
  212.         df["ShortTargetEMA_Hit"]         = df["HL2_XDn_Target_ChanBot"] & df["Active"]
  213.         #df["BuyToCover"]                = (df["XUpEma2"] & df["Active"]) | df["ActiveDiff"] == -1
  214.  
  215.  
  216.         df["AlgoActive"]               = True
  217.         df["NumSharesTraded"]           = 0.0
  218.         df["ValueSharesTraded"]         = 0.0
  219.         df["CashInHand"]               = np.NaN
  220.         df["CashInvested"]             = np.NaN
  221.         df["NumSharesHeld"]            = np.NaN
  222. #        df["ShareCost"]                = np.NaN
  223.         df["ValueSharesHeld"]          = np.NaN
  224.         df["AccountIsWorth"]           = np.NaN
  225.         df["Profit"]                   = np.NaN
  226.         df['BuyPrice']                 = np.NaN
  227.         df['SellPrice']                = np.NaN
  228.         df['ShortPrice']               = np.NaN
  229.         df['BtcPrice']                 = np.NaN
  230.         df['LongStopPrice']            = np.NaN
  231.         df['ShortStopPrice']           = np.NaN
  232.         df['LongTargetPrice']          = np.NaN
  233.         df['ShortTargetPrice']         = np.NaN
  234.         df['LTP1_Price']               = np.NaN
  235.         df['STP1_Price']               = np.NaN
  236.         df['TradeOpenPrice']           = np.NaN
  237.  
  238.         df['TheEnd']                   = False      #need this to check stop losses to end of data
  239.         df['TheEnd'][-1]               = True
  240.  
  241.         df2 = df[(df.GoLong == True) | #or
  242.                  (df.GoShort == True) | #or
  243.                  #(df.SellFlat == True) | # or
  244.                  #(df.BuyToCover == True) | # or
  245.                  (df.LTP1 == True) | # or
  246.                  (df.STP1 == True) | # or
  247.                  (df.LongStopEMA_Hit == True) | # or
  248.                  (df.ShortStopEMA_Hit == True) | # or
  249.                  (df.LongTargetEMA_Hit == True) | # or
  250.                  (df.ShortTargetEMA_Hit == True) | # or
  251.  
  252.                  (df.ActiveDiff == True) | # or
  253.                   df['TheEnd']
  254.                  ]
  255.  
  256.         if df2.shape[0] == 0:
  257.             return None
  258.  
  259.         self.cashInHand = 10000
  260.         df["CashInHand"][0] = 10000
  261.         self.numSharesHeld = 0
  262.  
  263.     #    rowIter = enumerate(df2.iterrows())
  264.         rowIter = df2.iterrows()
  265.         self.backfill_start_i = None
  266.         self.trade_open_price = 200           ## avoid blowup in MakeTrade(
  267.         self.TP1_Taken = False
  268.  
  269.         #for (today_i, today) in rowIter:
  270.         while (True):
  271.             try:
  272.                 data_i, data = rowIter.next()
  273.             except StopIteration:
  274.                 break
  275.  
  276.             trace = False
  277.             #if data_i > pd.Period(year = 2013, month = 11, day = 13, hour = 14, freq = "H"):
  278.             #    print "Its time"
  279.             #    #import pdb
  280.             #    #pdb.set_trace()
  281.             #    #trace = True
  282.             #    trace = True
  283.  
  284.  
  285.             self.someSharesTraded = False
  286.             self.close = data['Close']
  287.             self.NumSharesTraded = 0
  288.             self.ValueSharesTraded = 0
  289.  
  290.             if trace:
  291.                 print "data : " + str(data)
  292.  
  293.                 vars = ["LS_ema", "LS_width", "TP1_ema", "TP1_pct", "TP1_width", "TP1_profitWidth", "target_width", "stop_ema", "stop_ema_width", "stop_window",]
  294.                 print [(a,eval(a)) for a in vars]
  295.                 vars2 = ["self.numSharesHeld", "self.long_stop_price", "self.cashInHand", ]
  296.                 print [(a,eval(a)) for a in vars2]
  297.  
  298.             #First check if stops were hit..
  299.             if self.numSharesHeld > 0:                       # if long
  300.                 if self.backfill_start_i is not None:                  # sanity check
  301.                     df3 = df.loc[self.backfill_start_i:data_i]      # inclusive range so we shouldnt use backfill_start_i but instead use the next valid day.. Cant find how to do that in the book !
  302.                     df3['LongStopPrice'] = self.long_stop_price               #fill in the stop_price on preceeding days if we have a trade open
  303.                     df3['LongTargetPrice'] = self.long_target_price           #and the target price
  304.                     df3['TradeOpenPrice'] = self.trade_open_price
  305.                     df4 = df3[df3.Low < self.long_stop_price]
  306.                     if (df4.shape[0] > 0):
  307.                         sell_day_i = df4.index[0]
  308.                         if (sell_day_i == data_i):
  309.                             self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.long_stop_price, "SellPrice", None)
  310.                         else:
  311.                             self.MakeTrade(df, None, sell_day_i, -self.numSharesHeld, self.long_stop_price, "SellPrice", None)
  312.  
  313.                     df5 = df3[df3.High > self.long_target_price]
  314.                     if (df5.shape[0] > 0):
  315.                         sell_day_i = df5.index[0]
  316.                         if (sell_day_i == data_i):
  317.                             self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.long_target_price, "LTP1_Price", None)
  318.                         else:
  319.                             self.MakeTrade(df, None, sell_day_i, -self.numSharesHeld, self.long_target_price, "LTP1_Price", None)
  320.                 else:
  321.                     print "Insanity"
  322.             elif self.numSharesHeld < 0:                     #if short
  323.                 if self.backfill_start_i is not None:                  # sanity check
  324.                     df3 = df.loc[self.backfill_start_i:data_i]      # inclusive range so we shouldnt use backfill_start_i but instead use the next valid day.. Cant find how to do that in the book !
  325.                     df3['ShortStopPrice'] = self.short_stop_price           #fill in the stop_price on preceeding days if we have a trade open
  326.                     df3['ShortTargetPrice'] = self.short_target_price       #and the short target price
  327.                     df3['TradeOpenPrice'] = self.trade_open_price
  328.                     df4 = df3[df3.High > self.short_stop_price]
  329.                     if (df4.shape[0] > 0):
  330.                         btc_day_i = df4.index[0]
  331.                         if (btc_day_i == data_i):
  332.                             self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.short_stop_price, "BtcPrice", None)  ## this isnt quite righ.. price can gap past the stop price meaning it was impossible to attain
  333.                         else:
  334.                             self.MakeTrade(df, None, btc_day_i, -self.numSharesHeld, self.short_stop_price, "BtcPrice", None)  ## this isnt quite righ.. price can gap past the stop price meaning it was impossible to attain
  335.  
  336.                     df5 = df3[df3.Low < self.short_target_price]
  337.                     if (df5.shape[0] > 0):
  338.                         btc_day_i = df5.index[0]
  339.                         if (btc_day_i == data_i):
  340.                             self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.short_target_price, "STP1_Price", None)  ## this isnt quite righ.. price can gap past the stop price meaning it was impossible to attain
  341.                         else:
  342.                             self.MakeTrade(df, None, btc_day_i, -self.numSharesHeld, self.short_target_price, "STP1_Price", None)  ## this isnt quite righ.. price can gap past the stop price meaning it was impossible to attain
  343.                 else:
  344.                     print "Insanity short"
  345.  
  346.  
  347.             if data['LongStopEMA_Hit'] and self.numSharesHeld > 0:
  348.                 self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "SellPrice", None)
  349.             if data['ShortStopEMA_Hit'] and self.numSharesHeld < 0:
  350.                 self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "BtcPrice", None)
  351.            
  352.             if (data['GoLong']):
  353.                 if data["LongBias"]:
  354.                     if (self.numSharesHeld < 0):
  355.                         self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, None, None)
  356.                     if (self.numSharesHeld == 0):
  357.                         self.MakeTrade(df, data, data_i, self.cashInHand / self.close, self.close, "BuyPrice", data["LongRollingStopPrice"])
  358.                         self.long_stop_price = data["LongRollingStopPrice"]
  359.                         self.long_target_price = data["Target_EMA_ChanTop"] #data["TP1_EMA_ChanTop"]# data["Target_EMA_ChanTop"]
  360.                         self.TP1_Taken = False
  361.                 #else:
  362.                 #    if (self.numSharesHeld < 0):
  363.                 #        self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "BtcPrice")
  364.  
  365.             if (data['GoShort']):
  366.                 if data["ShortBias"]:
  367.                     if (self.numSharesHeld > 0):
  368.                         self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, None, None)
  369.                     if (self.numSharesHeld == 0):
  370.                         self.MakeTrade(df, data, data_i, -self.cashInHand / self.close, self.close, "ShortPrice", data["ShortRollingStopPrice"])
  371.                         self.short_stop_price = data["ShortRollingStopPrice"]
  372.                         self.short_target_price = data["Target_EMA_ChanBot"] #data["TP1_EMA_ChanBot"] #data["Target_EMA_ChanBot"]
  373.                         self.TP1_Taken = False
  374.                 #else:
  375.                 #    if (self.numSharesHeld > 0):
  376.                 #        self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "SellPrice")
  377.  
  378.             if (data['LTP1']):
  379.                 if data["LongBias"] == False:
  380.                     if self.numSharesHeld > 0:
  381.                         if self.TP1_Taken == False:
  382.                             if (self.close - self.trade_open_price) > (data["ChanWidth"] * TP1_profitWidth):
  383.                                 self.MakeTrade(df, data, data_i, -self.numSharesHeld * TP1_pct, self.close, "LTP1_Price", None)
  384.                                 self.TP1_Taken = True
  385.                             #else:
  386.                             #    print "Not enough profit - need " + str(data["ChanWidth"] * TP1_profitWidth) + ". But got : " + str(self.close - self.trade_open_price)
  387.             if (data['STP1']):
  388.                 if data["ShortBias"] == False:
  389.                     if self.numSharesHeld < 0:
  390.                         if self.TP1_Taken == False:
  391.                             if (self.close - self.trade_open_price) < -(data["ChanWidth"] * TP1_profitWidth):
  392.                                 self.MakeTrade(df, data, data_i, -self.numSharesHeld * TP1_pct, self.close, "STP1_Price", None)
  393.                                 self.TP1_Taken = True
  394.                             #else:
  395.                             #    print "Not enough profit - need " + str(data["ChanWidth"] * TP1_profitWidth) + ". But got : " + str(-(self.close - self.trade_open_price))
  396.             if data['TheEnd']:
  397.                 if self.numSharesHeld > 0:
  398.                     self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "SellPrice", None)
  399.                 elif self.numSharesHeld < 0:
  400.                     self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "BtcPrice", None)
  401.             if data["ActiveDiff"] < 0:
  402.                 if self.numSharesHeld > 0:
  403.                     self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "SellPrice", None)
  404.                 elif self.numSharesHeld < 0:
  405.                     self.MakeTrade(df, data, data_i, -self.numSharesHeld, self.close, "BtcPrice", None)
  406.  
  407.             if self.someSharesTraded:
  408.                 df.loc[data_i] = data    
  409.  
  410.             if self.numSharesHeld == 0:
  411.                 self.backfill_start_i = None    #nothing to fill
  412.             else:
  413.                 self.backfill_start_i = data_i  #keep moving this forward so we're filling in new date ranges with upto date values.
  414.  
  415.  
  416.         df["NumSharesHeld"].ffill(axis = 0, inplace = True)
  417.         df["CashInHand"].   ffill(axis = 0, inplace = True)
  418.         df["CashInvested"]. ffill(axis = 0, inplace = True)
  419. #        df["ShareCost"].    ffill(axis = 0, inplace = True)
  420.  
  421.         df["NumSharesHeld"].    fillna(0.0, inplace = True)
  422.  
  423.         t1 = np.abs(df['NumSharesHeld']) * df["TradeOpenPrice"]    
  424.         t1.fillna(0.0, inplace = True)
  425.  
  426.         t2 = df["Close"] - df["TradeOpenPrice"]     #has nulls   but good
  427.        
  428.         df['ValueSharesHeld']   =  t1 +  (t2 * df['NumSharesHeld']).fillna(0.0)
  429.         df['AccountIsWorth']    = df['CashInHand'].fillna(0.0) + df['ValueSharesHeld'].fillna(0.0)
  430.         df['Profit']            = df['AccountIsWorth'] - 10000.0
  431.  
  432.         df["CashInHand"].       fillna(0.0, inplace = True)            
  433.         df["CashInvested"].     fillna(0.0, inplace = True)            
  434. #        df["ShareCost"].        fillna(0.0, inplace = True)            
  435.         df["ValueSharesHeld"].  fillna(0.0, inplace = True)
  436.         df["AccountIsWorth"].   fillna(0.0, inplace = True)
  437.         df["Profit"].           fillna(0.0, inplace = True)
  438.  
  439.         return df
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement