packtpublishing / learn-algorithmic-trading Goto Github PK
View Code? Open in Web Editor NEWLearn Algorithmic Trading, Published by Packt
License: MIT License
Learn Algorithmic Trading, Published by Packt
License: MIT License
Hi there,
I checked this script, and i my opinion, there is a bug on a stage where open close pnl is calculated.
As a solution i propose make something like that:
if position > 0:
open_pnl = 0
if sell_sum_qty > 0: # long position and some sell trades have been made against it, close that amount based on how much was sold against this long position
open_pnl = abs(sell_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
# mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)
elif position < 0:
open_pnl = 0
if buy_sum_qty > 0: # short position and some buy trades have been made against it, close that amount based on how much was bought against this short position
open_pnl = abs(buy_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
# mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty / sell_sum_qty - close_price)
else:
# flat, so update closed_pnl and reset tracking variables for positions & pnls
closed_pnl += open_pnl
buy_sum_price_qty = 0
buy_sum_qty = 0
sell_sum_price_qty = 0
sell_sum_qty = 0
last_buy_price = 0
last_sell_price = 0
open_pnl = 0
In the tail end of the chapter 2 the concepts of seasonality is introduced along with some lines of code to help generate the graphs. Despite being listed like all other lines of code in the chapter, it is not written anywhere in this repository.
positions = pd.DataFrame(index=signals.index).fillna(0.0)
positions = pd.DataFrame(index=signals.index).fillna(0.0)
NameError: name 'signals' is not defined
In line 72, when defining the Sell_entry rationale for the first case (Short Entry) shouldn't we have:
apo > apo_value_sell_entry?
Since an APO above the threshold points to an uptrend in prices and thus a good moment to short the stock.
open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)
Above block of code is wrong. it should be open_pnl += abs(position)*(.........). Position is the amount the should be marked to market
xd im getting this error . thx for rewieving this issue , not sure if its a library mistake or something else ; as im a beginner ... thx for helping me out ( ;
D:\algo_trding_learning\venv\Scripts\python.exe D:\algo_trding_learning\buylowsellhigh.py
Traceback (most recent call last):
File "D:\algo_trding_learning\buylowsellhigh.py", line 5, in
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)
File "D:\algo_trding_learning\venv\lib\site-packages\pandas\util_decorators.py", line 213, in wrapper
return func(*args, **kwargs)
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\data.py", line 370, in DataReader
return YahooDailyReader(
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\base.py", line 253, in read
df = self._read_one_data(self.url, params=self._get_params(self.symbols))
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\yahoo\daily.py", line 153, in _read_one_data
data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers
Process finished with exit code 1
Chapter2\seasonality.py
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3803, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 2263, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 2273, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:*\Workspace\learn-algorithmic-trading\Chapter2\seasonality.py", line 26, in
'monthly_return': goog_monthly_return[i]})
File "C:\Python310\lib\site-packages\pandas\core\series.py", line 981, in getitem
return self._get_value(key)
File "C:\Python310\lib\site-packages\pandas\core\series.py", line 1089, in _get_value
loc = self.index.get_loc(label)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 2916, in get_loc
loc = self._get_level_indexer(key, level=0)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 3263, in _get_level_indexer
idx = self._get_loc_single_level_index(level_index, key)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 2849, in _get_loc_single_level_index
return level_index.get_loc(key)
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc
raise KeyError(key) from err
KeyError: 0
Hello,
I tried running the seasonality code and I am not able to run it. The first issue I notice is at line code 24. there is a typo instead of monthly im seeing montly.
its also missing index for 'monthly_return.
there is also an issue in line code 28 and 31 with the boxplot call function.
In this part of ch4_turtle_trading.py, shouldn't in the last two elif
statements "short_exit" and "long_exit" be swapped? Since if position > 0
then we are long and there should be a long exit and not a short exit and vice versa.
init=True
position=0
for k in range(len(signals)):
if signals['long_entry'][k] and position==0:
signals.orders.values[k] = 1
position=1
elif signals['short_entry'][k] and position==0:
signals.orders.values[k] = -1
position=-1
elif signals['short_exit'][k] and position>0:
signals.orders.values[k] = -1
position = 0
elif signals['long_exit'][k] and position < 0:
signals.orders.values[k] = 1
position = 0
else:
signals.orders.values[k] = 0
return signals
The code of Seasonality does not work properly. when we copy paste the code an error occurs. I am using the 3.9 version python. I believe the problem is in this section:
goog_monthly_return = goog_data['Adj Close'].pct_change().groupby(
[goog_data['Adj Close'].index.year,
goog_data['Adj Close'].index.month]).mean()
goog_montly_return_list=[]
for i in range(len(goog_monthly_return)):
goog_montly_return_list.append
({'month':goog_monthly_return.index[i][1],
'monthly_return': goog_monthly_return[i]})
Great Book Thank you for Author, Lot of best wishes !
I am getting an error on the 4th line of the first chapter, any idea ?
from pandas_datareader import data
start_date = '2014-01-01'
end_date = '2018-01-01'
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)
ERROR:
data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers
author line 106 : open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)
position -= NUM_SHARES_PER_TRADE # reduce position by the size of this trade
sell_sum_qty += NUM_SHARES_PER_TRADE
so the remaining position : abs(position)
Line 106 : open_pnl += abs(position) * (close_price - buy_sum_price_qty / buy_sum_qty)
and the author line 111 : open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty/sell_sum_qty - close_price)
also need to be corrected:
Line 111 : open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty/sell_sum_qty - close_price)
Note: abs(position) = abs(buy_sum_qty-sell_sum_qty)
I think I found some bug in Chapter 7: LiquidityProvider.py
def lookup_orders(self, id)
(line 11) returns a tuple of (None, None)
or (o, count)
.
But generate_random_order(self)
lines 35-40 compares the tuple with a None
, making new_order
always False
And line 52, shouldn't it be if new_order
instead of if not new_order
? If it is a new_order, we want to increase the order_id
and append the new order ord
to self.orders
Hello,
I keep getting the following bug when trying to run the unit test for Trading Strategy.
TradingStrategy_ut.py::TestMarketSimulator::test_filled_order FAILED [ 33%]
TradingStrategy_ut.py:45 (TestMarketSimulator.test_filled_order)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_filled_order>
def setUp(self):
> self.trading_strategy= TradingStrategy()
E TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'
TradingStrategy_ut.py:8: TypeError
FAILED [ 66%]
TradingStrategy_ut.py:10 (TestMarketSimulator.test_receive_top_of_book)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_receive_top_of_book>
def setUp(self):
> self.trading_strategy= TradingStrategy()
E TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'
TradingStrategy_ut.py:8: TypeError
FAILED [100%]
TradingStrategy_ut.py:29 (TestMarketSimulator.test_rejected_order)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_rejected_order>
def setUp(self):
> self.trading_strategy= TradingStrategy()
E TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'
TradingStrategy_ut.py:8: TypeError
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.