首页 > 解决方案 > 从列中引用索引并添加计数

问题描述

在下面我的项目之后,我希望 python 能够显示交易的日期。目前我已经做了一个回测,显示价格是高于平均水平还是低于平均水平。有没有一种方法可以在结果中指定交易(买入和卖出)完成的日期?例如“在 2019 年 5 月 20 日以 5.86999 现在购买”。是否可以为我所做的交易添加计数?

### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12
Slow_EMA = 26
Signal_EMA = 9
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 1% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = 0
selltrades = 0
percentchange = []
cut_loss_percent = 0.96
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price        
            pos = 1
            buytrades =+1
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp))
            print('Will cut loss at ' + str (cut_loss))



    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss))
               pos = 0
               selltrades =+1
               print(cut_loss - bp)
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades =+1
            print('Selling now at ' + str(cp))
            print(cp-bp)
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)            


if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)




total_realizedpnl = sum(realized_pnl)
print('Realized Pnl '+ str(total_realizedpnl))
All_pnl = total_realizedpnl + mtm
print('Sum of total Pnl ' + str(All_pnl))
sum(percentchange)

下面是结果的片段

MACD higher than Signal
Buying now at 5.869999885559082
Will cut loss at 5.635199890136718
MACD higher than Signal
...
MACD higher than Signal
Still has position in place
Realized Pnl 4.460401210784912
Sum of total Pnl 5.5204016304016115
Out[21]:
0.6354297951321523

标签: pythonpandasdataframe

解决方案


设法找到解决方法,这可能很白痴,但不知何故我工作:D

### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12 #Amend as you like
Slow_EMA = 26 #Amend as you like
Signal_EMA = 9 #Amend as you like
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()
df['MACD_Sig_diff'] = df['MACDLine'] - df['Signal_Line']
df['MACD_Sig_diff_10MA'] = df['MACD_Sig_diff'].ewm(span = 10, min_periods = 10).mean()
df['Date'] = df.index

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 4% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = []
selltrades = []
percentchange = []
cut_loss_percent = 0.96 #Stop loss level, if its 5% it will be 100% - 5% = 0.95
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    tradedate = df['Date'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price        
            pos = 1
            buytrades.append(1)
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp) +' at ' + str(tradedate))
            print('Will cut loss at ' + str (cut_loss))



    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss)+' at ' + str(tradedate))
               pos = 0
               selltrades.append(1)
               print('Pnl is ' + str(cut_loss - bp))
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades.append(1)
            print('Selling now at ' + str(cp)+' at ' + str(tradedate))
            print('Pnl is '+ str(cp-bp))
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)            


if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)





print('Realized Pnl '+ str(sum(realized_pnl)))
All_pnl = realized_pnl + mtm
print('Sum of total Pnl ' + str(sum(All_pnl)))
print('Pnl in % ' +str(sum(percentchange*100)))
print('The number of buy trades are ' + str(sum(buytrades)))
print('The number of sell trades are '+ str(sum(selltrades)))


推荐阅读