如何在Python代码中设置止损和获利?

时间:2020-11-02 15:07:07

标签: trading algorithmic-trading back-testing technical-indicator

我正在尝试对Jupyter Notebook上的股票交易策略进行回测。编码如下,包括策略和确定何时购买股票(在这种情况下为MSFT / Microsoft)。但是,我无法提供一个代码来记录每次交易后的盈亏。因此,要求代码执行以下操作:

(1)当股票收盘价比我的买入/交易价高出3%(获利)时卖出 (2)当股票收盘价低于我的买入/交易价格(账面亏损)的2%时卖出 (3)计算所有交易后的总损益

感谢您是否可以帮助这位python新手回测他的第一个策略。很高兴提供更多说明。

#import库

import pandas as pd
import numpy as np
import datetime as dt
import yfinance as yf
import matplotlib as plt
import talib


**#define a function to extract stock data from yfinance**

def asset_data(ticker, start_date, end_date):
    data = yf.download(ticker, start_date, end_date)
    return data
ticker = 'MSFT'
start_date = dt.date(2010, 1, 1)
end_date = dt.date(2014, 12, 31)
df = asset_data(ticker, start_date, end_date)
df.head()

****#add exponential moving averages****

df['EMA10'] = talib.EMA(df['Close'],10)
df['EMA20'] = talib.EMA(df['Close'],20)
df['EMA30'] = talib.EMA(df['Close'],30)
df[['EMA10','EMA20','EMA30']].plot(figsize = (20,15))

**#generate trading signal based on the below conditions and calculate profit/losses**

df['Signal'] = np.where((df['EMA10']>df['EMA20'])&(df['EMA20']>df['EMA30']),1,0)

**#this is my work to figure out a solution but I know it's incorrect**

df['Final_Signal'] = np.where((df['Signal']==1)&(df['Signal'].shift(1)==0),1,0)
df['Trading_Price'] = df['Close'].where(df['Final_Signal']==1)
df['Trading_Price'] = df['Trading_Price'].ffill()
df['Returns'] = (df['Close']-df['Trading_Price'])/df['Trading_Price']
df['Square_Off'] = np.where(df['Returns']>=-0.03,'Profit',0)
df.tail()

0 个答案:

没有答案