给定具有形状(n,k)的矩阵A和大小为n的向量s,我想要计算具有形状(k,k)的矩阵G,如下所示:
对于{0,...,n-1}中的所有i,G + = s [i]*A [i] .T*A [i]
我尝试使用for循环(方法1)和矢量化方法(方法2)来实现它,但对于大的k值(特别是当k> 500时),for循环实现更快.
代码编写如下:
import numpy as np
k = 200
n = 50000
A = np.random.randint(0, 1000, (n,k)) # generates random data for the matrix A (n,k)
G1 = np.zeros((k,k)) # initialize G1 as a (k,k) matrix
s = np.random.randint(0, 1000, n) * 1.0 # initialize …Run Code Online (Sandbox Code Playgroud) 鉴于此示例数据帧:
date;close;signal;positions
2017-01-02;27.90;0.0;0.0
2017-01-03;27.76;0.0;0.0
2017-01-04;28.65;1.0;1.0
2017-01-05;28.72;1.0;0.0
2017-01-06;28.00;1.0;0.0
2017-01-09;27.03;1.0;0.0 # <<<--- Note the price is -5% when compared to 28.65 (in 2017-01-04)
2017-01-10;28.26;1.0;0.0
2017-01-11;28.35;0.0;-1.0 # <<-- Sell
2017-01-12;29.12;0.0;0.0
2017-01-13;28.99;0.0;0.0
2017-01-16;28.50;1.0;1.0
2017-01-17;28.45;1.0;0.0
2017-01-18;29.06;1.0;0.0
2017-01-19;28.74;0.0;-1.0
2017-01-20;28.76;0.0;0.0
2017-01-23;29.50;0.0;0.0
2017-01-24;29.12;1.0;1.0
2017-01-25;29.87;1.0;0.0
2017-01-26;27.22;1.0;0.0 # <<<--- Note the price is -5% when compared to 29.12 (in 2017-01-24)
2017-01-27;29.76;1.0;0.0 # <<-- still holding the position...
Run Code Online (Sandbox Code Playgroud)
我想在价格低于 5% 时实施“止损”。在这种情况下,DataFrame 应如下所示:
date;close;signal;positions
2017-01-02;27.90;0.0;0.0
2017-01-03;27.76;0.0;0.0
2017-01-04;28.65;1.0;1.0 # <<-- Buy
2017-01-05;28.72;1.0;0.0
2017-01-06;28.00;1.0;0.0
2017-01-09;27.03;0.0;-1.0 # <<-- Sell with stop-loss
2017-01-10;28.26;0.0;0.0
2017-01-11;28.35;0.0;0.0
2017-01-12;29.12;0.0;0.0
2017-01-13;28.99;0.0;0.0 …Run Code Online (Sandbox Code Playgroud)