An open API service indexing awesome lists of open source software.

https://github.com/nasdin/tradehistgen

Generate random trade histories given a time series price data. Which can later be used to filter certain trade transactions which meets criteria
https://github.com/nasdin/tradehistgen

Last synced: 3 months ago
JSON representation

Generate random trade histories given a time series price data. Which can later be used to filter certain trade transactions which meets criteria

Awesome Lists containing this project

README

        

```python
import numpy as np
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

```

## Random Market Trade Generator, batch of trades

```python
sns.set()
spread = 0 #Assume Spread In Pips
```

### Simulation Size

```python
SimSize = 100000
```

#### Pip Range base area

```python
base = 50
```

#### Random Generators

```python
randomtrades = np.random.randint(0,high=2,size=SimSize)

tradeid = range(SimSize,SimSize*2)

PipModifier = (np.random.normal(size=SimSize))
```

### Risk Reward Simulation
Assume that the average Risk Reward is at least 2 ( like a typical Trader would try and filter by)

```python
RiskReward = np.random.binomial(n = 14, p = 0.3,size=SimSize)
# I intended to make it a max of RR 7, I use 14 where I will divide by 2 later as a float to get a intervals of 0.5
RiskReward = (RiskReward + 1)/2. # Gets rid of 0 and makes it a float too.
```

#### Check the min and average

```python
print np.min(RiskReward),np.mean(RiskReward)
```

0.5 2.60035

#### Logically you should expect the Risk Reward to be a binomial distribution such as this,
based on market volatility, the skew should be towards the left, as I've placed the parameter p = 0.3

```python
sns.distplot(RiskReward)
plt.show()
```

![png](output_14_0.png)

#### Headers and inferences

```python
Header = [ 'TradeId','Direction','Size','SLPips', 'TPPips', 'OutcomePips','Outcome$', 'AccumulativeOutcomePips', 'AccumulativeOutcome']
```

```python
sizerange = [ 0.1 for i in range(SimSize)]
Direction = ['Buy' if direction == 1 else 'Sell' for direction in randomtrades ]
```

### SL
The distribution generates including negative numbers so we have to do a mathematical perturbation.
We'll do that by simply adding the abs of the minimum amount.
This way, the lowest value will become 0. However, the numbers are all inflated.
We will then have to divide it by the amount it was inflated by

```python
def GenSL(base=base, PipModifier=PipModifier):
first = (base *PipModifier) # The normal distribution but with negative values and positive value
minamt = abs(np.min(first)) # Amount to shift it by
ratio = minamt/base # Amount that it was inflated by
output = (first + minamt ) /4
return output*-1 #output should be negative for SL

```

#### Same transformation for TP, except Tp is multiplied with Risk : Reward Ratio as a multiplier

```python
def GenTP(base=base, PipModifier=PipModifier, RiskReward=RiskReward):
first = (base *PipModifier) * RiskReward # The normal distribution but with negative values and positive value
minamt = abs(np.min(first)) # Amount to shift it by
ratio = minamt/base # Amount that it was inflated by

return (first + minamt ) /4

```

```python
sns.distplot(GenSL(),bins=50, color = 'r')
plt.show()

```

![png](output_22_0.png)

```python
sns.distplot(GenTP(),bins=50, color = 'g')
plt.show()
```

![png](output_23_0.png)

### Create the TP and SL array

```python
TPPips = GenTP()
SLPips = GenSL()
```

#### Win/Loss based on Efficient Market Hypothesis

#### Calculate Probability to Win on Random

```python
def Prob(TP,SL):
Total = TP + abs(SL)
pb = abs(SL) / Total
return pb
```

```python
WinLoss = [ 1 if np.random.random() < Prob(TP,SL) else 0 for TP, SL in zip(TPPips,SLPips)]
```

### Get the Outcome, Pips
Since this is going to be in a large loop, we'll produce it via a list comprehension

```python
OutcomePips = [TPPips[index] -spread if win==1 else SLPips[index] for index,win in enumerate(WinLoss)]
```

##### Accumulative Outcome Pips
Accumulative Pips is a step by step iterative accumulative code so a classic for loop will do

```python
AccumulativePips =[]
Totalpips =0
for index,pips in enumerate(OutcomePips):
Totalpips += pips
AccumulativePips.append(Totalpips)

```

```python
data = [ tradeid, Direction, SLPips, TPPips, WinLoss,OutcomePips,AccumulativePips]
```

### Create the Panda Dataframe

```python
Tradehistory = pd.DataFrame( {'TradeId': tradeid, 'Direction':Direction, 'SLPips':SLPips, 'TPPips':TPPips, 'WinLoss':WinLoss, 'ResultPips':OutcomePips,'PipP&L':AccumulativePips})
```

```python
Tradehistory
```

.dataframe thead tr:only-child th {
text-align: right;
}

.dataframe thead th {
text-align: left;
}

.dataframe tbody tr th {
vertical-align: top;
}




Direction
PipP&L
ResultPips
SLPips
TPPips
TradeId
WinLoss




0
Buy
227.475250
227.475250
-64.979820
227.475250
100000
1


1
Sell
152.450761
-75.024489
-75.024489
277.161225
100001
0


2
Buy
72.055682
-80.395079
-80.395079
295.958290
100002
0


3
Sell
26.886834
-45.168848
-45.168848
167.604208
100003
0


4
Sell
-20.804392
-47.691226
-47.691226
189.096976
100004
0


5
Buy
-48.693098
-27.888706
-27.888706
112.185986
100005
0


6
Buy
-110.667076
-61.973978
-61.973978
218.123275
100006
0


7
Sell
105.780599
216.447674
-58.075154
216.447674
100007
1


8
Buy
48.406640
-57.373959
-57.373959
210.182965
100008
0


9
Sell
-4.155811
-52.562451
-52.562451
198.544093
100009
0


10
Sell
-64.708452
-60.552641
-60.552641
231.769001
100010
0


11
Sell
-107.369762
-42.661311
-42.661311
189.154274
100011
0


12
Sell
-172.440583
-65.070820
-65.070820
237.434674
100012
0


13
Buy
-235.751204
-63.310621
-63.310621
220.128240
100013
0


14
Buy
-17.244955
218.506249
-60.495320
218.506249
100014
1


15
Buy
-72.993676
-55.748721
-55.748721
209.696037
100015
0


16
Buy
-129.647233
-56.653557
-56.653557
212.862964
100016
0


17
Buy
-146.388342
-16.741109
-16.741109
92.445539
100017
0


18
Sell
-200.151292
-53.762951
-53.762951
205.806734
100018
0


19
Sell
-267.387836
-67.236543
-67.236543
243.931843
100019
0


20
Sell
-325.763639
-58.375803
-58.375803
215.808419
100020
0


21
Buy
-364.654439
-38.890800
-38.890800
191.699807
100021
0


22
Sell
-434.593362
-69.938923
-69.938923
274.007270
100022
0


23
Buy
-476.937072
-42.343711
-42.343711
169.253345
100023
0


24
Sell
-532.785022
-55.847950
-55.847950
209.766062
100024
0


25
Buy
-597.804277
-65.019255
-65.019255
242.142906
100025
0


26
Buy
-654.063179
-56.258902
-56.258902
210.998920
100026
0


27
Buy
-449.221278
204.841901
-53.989196
204.841901
100027
1


28
Sell
-523.574188
-74.352911
-74.352911
265.280945
100028
0


29
Buy
-568.342483
-44.768295
-44.768295
192.314750
100029
0


...
...
...
...
...
...
...
...


99970
Sell
16129.466956
-45.894166
-45.894166
179.904710
199970
0


99971
Sell
16059.938494
-69.528462
-69.528462
236.572534
199971
0


99972
Sell
15994.415308
-65.523186
-65.523186
233.676876
199972
0


99973
Sell
15956.083839
-38.331469
-38.331469
148.735656
199973
0


99974
Sell
15921.753577
-34.330262
-34.330262
145.212998
199974
0


99975
Sell
15858.064074
-63.689503
-63.689503
224.894616
199975
0


99976
Sell
15802.677835
-55.386240
-55.386240
208.380932
199976
0


99977
Buy
16001.972741
199.294907
-52.357565
199.294907
199977
1


99978
Sell
15931.069102
-70.903639
-70.903639
239.322888
199978
0


99979
Sell
15879.592734
-51.476368
-51.476368
200.468346
199979
0


99980
Sell
16097.347237
217.754503
-59.154237
217.754503
199980
1


99981
Buy
16055.746008
-41.601229
-41.601229
167.025900
199981
0


99982
Sell
16007.710736
-48.035272
-48.035272
193.586153
199982
0


99983
Buy
15940.329676
-67.381061
-67.381061
238.321563
199983
0


99984
Buy
16137.220020
196.890345
-51.556044
196.890345
199984
1


99985
Sell
16063.727250
-73.492770
-73.492770
271.800210
199985
0


99986
Buy
16265.927113
202.199862
-53.817762
202.199862
199986
1


99987
Sell
16195.241954
-70.685159
-70.685159
246.581808
199987
0


99988
Sell
16142.556237
-52.685718
-52.685718
201.583206
199988
0


99989
Buy
16084.619852
-57.936385
-57.936385
218.674354
199989
0


99990
Sell
16007.755379
-76.864473
-76.864473
240.459018
199990
0


99991
Sell
15967.397613
-40.357765
-40.357765
163.295509
199991
0


99992
Buy
16206.001733
238.604120
-64.008173
238.604120
199992
1


99993
Sell
16415.813089
209.811356
-56.432699
209.811356
199993
1


99994
Buy
16623.669802
207.856713
-55.211500
207.856713
199994
1


99995
Buy
16580.549144
-43.120658
-43.120658
189.843295
199995
0


99996
Buy
16534.117075
-46.432069
-46.432069
159.365102
199996
0


99997
Buy
16794.045401
259.928326
-68.249878
259.928326
199997
1


99998
Sell
16988.465860
194.420459
-48.452425
194.420459
199998
1


99999
Buy
17277.398427
288.932567
-87.625462
288.932567
199999
1

100000 rows × 7 columns


```python
print Tradehistory.info()
print Tradehistory.describe()
```


RangeIndex: 100000 entries, 0 to 99999
Data columns (total 7 columns):
Direction 100000 non-null object
PipP&L 100000 non-null float64
ResultPips 100000 non-null float64
SLPips 100000 non-null float64
TPPips 100000 non-null float64
TradeId 100000 non-null int64
WinLoss 100000 non-null int64
dtypes: float64(4), int64(2), object(1)
memory usage: 5.3+ MB
None
PipP&L ResultPips SLPips TPPips \
count 100000.000000 100000.000000 100000.000000 100000.000000
mean -881.153441 0.172774 -55.315874 208.131656
std 5881.943018 109.298843 12.527011 34.282536
min -16748.490652 -106.180121 -118.863214 0.000000
25% -4571.669642 -61.106808 -63.816824 187.893533
50% -1197.372069 -50.883573 -55.278750 208.068400
75% 2280.124517 -34.679912 -46.842749 228.355461
max 17277.398427 382.483281 -0.000000 412.632627

TradeId WinLoss
count 100000.000000 100000.000000
mean 149999.500000 0.208840
std 28867.657797 0.406482
min 100000.000000 0.000000
25% 124999.750000 0.000000
50% 149999.500000 0.000000
75% 174999.250000 0.000000
max 199999.000000 1.000000

### This is the Pip Accumulated curve over time, or the ROI of the account over time.
Assuming that the Lot / volume size entered into the market is fixed, then this would be the balance graph you would get in a efficient market hypothesis after SimSize( default is 100k) amount of trades done

```python
Tradehistory['PipP&L'].plot()
```

![png](output_40_1.png)

## Performing a bayesian generation on the accounts
We're going to simulate a few thousand accounts, all placing trades on a random and unpredictable market.

## The above steps was used to generate just 1 account's portfolio of trades
We will have to create a function to automate that process and that loop it a few thousand times