如何评估您的股票交易模型

Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.

Towards Data Science编辑的注意事项: 尽管我们允许独立作者按照我们的 规则和指南 发表文章 ,但我们不认可每位作者的贡献。 您不应在未征求专业意见的情况下依赖作者的作品。 有关 详细信息, 请参见我们的 阅读器条款

When I observe the occasional “Predicting Stock Price using LSTMs”, the measure of accuracy and profitability is loss, usually the mean squared error function. This is all well and good, for datasets in which the accuracy of the predicted value is the ultimate goal.

当我偶尔看到“使用LSTM预测股票价格”时,准确性和获利能力的度量是损失,通常是均方误差函数。 对于预测值的准确性是最终目标的数据集,这一切都很好。

In the case of stock trading, profitability is the ultimate goal. So how can we quantify this value?

在股票交易中,盈利是最终目标。 那么我们如何量化这个值呢?

概念: (Concept:)

The optimum value to evaluate the model should be directly related to the ultimate goal of the program, the profitability. So we know that the script should be able to evaluate the estimated profitability.

评估模型的最佳值应直接与计划的最终目标即获利能力相关。 因此,我们知道脚本应该能够评估估计的获利能力。

Additionally, to make the profitability estimator, the program has to work on data it has never seen before. This means we have to take a testing sample of the data, to check how much money one would make.

此外,要进行获利能力估算,该程序必须处理从未见过的数据。 这意味着我们必须对数据进行测试样本,以检查一个人能赚多少钱。

With the two most important traits of the profit estimation program, let’s get to creating the program.

有了利润估算程序的两个最重要的特征,让我们开始创建程序。

代码: (The Code:)

I have prepared three different scripts for different types of trading:

我为不同类型的交易准备了三种不同的脚本:

  • Fixed Time Trading

    固定时间交易
  • Normal Stock Trading

    普通股票交易
  • Binary Options Trading

    二元期权交易

固定交易时间: (Fixed TimeTrading:)

def trading_simulator(trade_time,trade_value,close_price,sma_one,sma_two):
intersections,insights = intersection(sma_1,sma_2)
profit = 0
logs = []
for i in range(len(insights)):
index = intersections[i]
if insights[i] == buy:
if index+trade_time < len(fx_data):
if fx_data[index][-1] < fx_data[index+trade_time][-1]:
profit += trade_value * 0.8
logs.append(trade_value*0.8)
elif fx_data[index][-1] > fx_data[index+trade_time][-1]:
profit -= trade_value
logs.append(-trade_value)
elif insights[i] == sell:
if index+trade_time <= len(fx_data):
if fx_data[index][-1] > fx_data[index+trade_time][-1]:
profit += trade_value * 0.8
logs.append(trade_value*0.8)
elif fx_data[index][-1] < fx_data[index+trade_time][-1]:
profit -= trade_value
logs.append(-trade_value)
profit = profit
return profit,logs

This trading program uses the intersection of two SMA values to test how much money would be made, if a trade was opened based on the insight of the intersection of two defined SMA values, along with the accuracy: The number of profitable trades out of all trades.

该交易程序使用两个SMA值的交集来测试赚取多少钱,如果基于两个定义的SMA值的交集的洞察力开仓了交易,则其准确性如下:所有交易中获利的交易数量交易。

This program bases the profit estimation based on fixed time trading: A trading strategy in which you predict in the next timeframe if the price will increase or decrease. You can either adapt the program, or just copy the entire script from here to test the profit estimation:

该程序基于固定时间交易进行利润估算:这是一种交易策略,您可以在下一个时间范围内预测价格会上涨还是下跌。 您可以改编程序,也可以从此处复制整个脚本以测试利润估算:

import requests
import numpy as np
from matplotlib import pyplot as plt
import datetime
API_KEY = 'YOURAPIKEYHERE'
from_symbol = 'EUR'
to_symbol = 'USD'def sell():
pyautogui.click(1350,320)
def buy():
pyautogui.click(1350,250)
def SMA(prices,value):
means = [] count = 0
while value+count <= len(prices):
pre_val = prices[count:value+count]
count +=1
means.append(np.mean(pre_val))
return meansdef intersection(lst_1,lst_2):
intersections = []
insights = []
if len(lst_1) > len(lst_2):
settle = len(lst_2)
else:
settle = len(lst_1)
for i in range(settle-1):
if (lst_1[i+1] < lst_2[i+1]) != (lst_1[i] < lst_2[i]):
if ((lst_1[i+1] < lst_2[i+1]),(lst_1[i] < lst_2[i])) == (True,False):
insights.append(buy)
else:
insights.append(sell)
intersections.append(i)
return intersections,insightsdef trading_simulator(trade_time,trade_value,close_price,sma_one,sma_two):
intersections,insights = intersection(sma_1,sma_2)
profit = 0
logs = []
for i in range(len(insights)):
index = intersections[i]
if insights[i] == buy:
if index+trade_time < len(fx_data):
if fx_data[index][-1] < fx_data[index+trade_time][-1]:
profit += trade_value * 0.8
logs.append(trade_value*0.8)
elif fx_data[index][-1] > fx_data[index+trade_time][-1]:
profit -= trade_value
logs.append(-trade_value)
elif insights[i] == sell:
if index+trade_time <= len(fx_data):
if fx_data[index][-1] > fx_data[index+trade_time][-1]:
profit += trade_value * 0.8
logs.append(trade_value*0.8)
elif fx_data[index][-1] < fx_data[index+trade_time][-1]:
profit -= trade_value
logs.append(-trade_value)
profit = profit
return profit,logsclose_price = []
r = requests.get(
'https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=' +
from_symbol + '&to_symbol=' + to_symbol +
'&interval=1min&outputsize=full&apikey=' + API_KEY)
jsondata = json.loads(r.content)
pre_data = list(jsondata['Time Series FX (1min)'].values())
fx_data = []
for data in pre_data:
fx_data.append(list(data.values()))
fx_data.reverse()
for term in fx_data:
close_price.append(float(term[-1]))sma_1 = SMA(close_price,2)
sma_2 = SMA(close_price,1)
profit,logs = trading_simulator(1,10,close_price,sma_1,sma_2)
profit

For the program to work, you must replace the API key parameter with your own API key from Alphavantage.

为了使程序正常运行,您必须使用Alphavantage的API密钥替换API密钥参数。

正常交易: (Normal Trading:)

Normal Trading is when a number of shares are bought or sold, and the profit made is the difference in the price of the shares.

正常交易是指购买或出售许多股份时,所获利润是股份价格之差。

def estimate_profits(standard_qty,model,data,close,open_,high,low):
close_prices = close
open_prices = open_
low_prices = low
high_prices = high
pred_close = list()
pred_open = list()
orders = list()
profits = list()
for i in range(len(data)):
pred = model.predict(data[i])[0]
open_price,close_price = pred
if open_price > close_price:
side = -1
elif open_price < close_price:
side = 1
qty = standard_qty
orders.append([side,qty])
pred_close.append(close_price)
pred_open.append(open_price)
for i in range(len(data)):
sign = 0
mult = 0
side,qty = orders[i][0],orders[i][1]
dif = close_prices[i] - open_prices[i]
if dif > 0:
sign = 1
else:
sign = -1
if sign == side:
mult = 1
else:
mult = -1
profit = dif*mult*qty
profits.append(profit)
return profits

This program calculates the difference between the asset between the time in which it has been made and the next time. It multiplies this difference by the quantity of shares to calculate the profit. You can adapt the time steps, to test longer period trading strategies.

该程序计算资产制造时间与下一次资产之间的差额。 将此差额乘以股份数量即可计算出利润。 您可以调整时间步长,以测试较长时期的交易策略。

二元期权交易: (Binary Options Trading:)

def trading_simulator(open_prices):
profit = 0
insights = []
logs = []
for i in range(len(pred)):
if float(open_prices[i]) > pred[i][0]:
insights.append('sell')
elif float(open_prices[i]) < pred[i][0]:
insights.append('buy')
for i in range(len(insights)):
if insights[i] == 'sell':
if float(open_prices[i]) > y[i]:
profit += 8
logs.append(8)
else:
profit -= 10
logs.append(-10)
if insights[i] == 'buy':
if float(open_prices[i]) < y[i]:
profit += 8
logs.append(8)
else:
profit -= 10
logs.append(-10)
return profit,logs

This function calculates the profits, considering a fixed 80% profit from the trade amount. It calculates the difference between the current value, and the value for the next time-step.

考虑到交易金额的固定80%利润,此函数计算利润。 它计算当前值和下一个时间步的值之间的差。

结论: (Conclusion:)

I really hope that people can use the profitability of the program to evaluate their model in-order to gain true insight of if the trading algorithm works.

我真的希望人们可以使用该程序的盈利能力来评估他们的模型,以便真正了解交易算法是否有效。

Thank you for reading my article!

感谢您阅读我的文章!

翻译自: https://towardsdatascience.com/how-to-evaluate-your-stock-trading-model-e7e5e51d4320

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值