Forex Python
Forex Python
The starting point is an Excel file containing nearly 35,000 data entries presented as shown in
the snapshot figures below. All data was imported into Python and pandas was used for writing
computational algorithms.
When plotted, the bid-ask spread and the trades look as shown in these graphs:
Scenario 1
Consider the situation where we hedge none of these client trades. Our position
begins flat (zero) and we are put into positions as the clients buy and sell to us.
Work out what our position and PnL looks like over the day.
Answer: The time index for the data in the two original sheets does not match. For the
two sheets to be processed together, the data was resampled so that time indices in the
two sheets match exactly. The resampling was done every minute even if the original
time index was spaced in milliseconds. Some granularity was lost - some transactions
that occurred within one minute are no longer recorded individually, but the total amount
traded in one minute is still there. The two sheets were then matched in one file
(dataframe). An excerpt of the code is shown below:
Scenario 2
Assume you can hedge our position at any time buy buying or selling in the
market at the price at that time. You are aggressing (crossing the spread), so will
buy on the offer price or sell on the bid price. Without using any information about
the client, repeat the PnL analysis from Scenario 1.
Answer: In the second case, the unrealized PnL was calculated similarly as in Case 1,
except that if traded amounts were negative at a time index posiiton, unrealized PnL
was obtained by multiplying the bid price by amount traded. When the traded amount
was positive, the offer price was multiplied by the amount to calculate the unrealized
PnL. As in Scenario 1, for positive traded amounts a position of long was noted, with
the reverse true for negative amounts that were labeled short. Excerpt code:
N = len(trans3)
for k in range(N):
if unrealized_PnL_1[k] < 0:
position1[k] = 'short'
The number of pips were calculated by noting the change in either bid price (for negative
traded amounts) or offer price (for positive traded amounts) from one time index to the
next. Results are shown in a column called pip2. The value of one pip for each time
index was calculated by multiplying pip2 by unrealized PnL for this Scenario 2. Results
are shown in a column called pip_value2. Excerpt code:
for y in range(N):
if amount[y]<0:
pip2[y] = bid[y] - bid[y-1]
else:
pip2[y] = offer[y] - offer[y-1]
trans3['pip2']=pip2
trans3['pip_value2'] = pd.DataFrame(trans3.pip2 * trans3.unrealized_PnL_2,
index = trans3.index, columns=['pip_value2'])