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

问题描述

我正在尝试对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,end_date)
    return data
ticker = 'MSFT'
start_date = dt.date(2010,1,1)
end_date = dt.date(2014,12,31)
df = asset_data(ticker,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']),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),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()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...