Algorithmic Trading with Python and Backtrader (Part 3)
HTML-код
- Опубликовано: 29 сен 2024
- Like the video? Support my content by signing up for Interactive Brokers using the link below:
www.interactiv...
In this video, we code the Sell strategy and visualize our final results using the plot() method.
Buy Me a Coffee: buymeacoffee.c...
Twitter: / parttimelarry
Website: hackingthemark...
Source Code: github.com/hac...
This content is provided by a paid Influencer of Interactive Brokers. Influencer is not employed by, partnered with, or otherwise affiliated with Interactive Brokers in any additional fashion. This content represents the opinions of Influencer, which are not necessarily shared by Interactive Brokers. The experiences of the Influencer may not be representative of other customers, and nothing within this content is a guarantee of future performance or success.
None of the information contained herein constitutes a recommendation, promotion, offer, or solicitation of an offer by Interactive Brokers to buy, sell or hold any security, financial product or instrument or to engage in any specific investment strategy. Investment involves risks. Investors should obtain their own independent financial advice and understand the risks associated with investment products and services before making investment decisions. Risk disclosure statements can be found on the Interactive Brokers website.
Interactive Brokers is a FINRA registered broker and SIPC member, as well as a National Futures Association registered Futures Commission Merchant. Interactive Brokers provides execution and clearing services to its customers. For more information regarding Interactive Brokers or any Interactive Brokers products or services referred to in this video, please visit www.interactivebrokers.com
Like the video? Support my content by signing up for Interactive Brokers using the link below:
www.interactivebrokers.com/mkt/?src=ptlPY1&url=%2Fen%2Findex.php%3Ff%3D1338
i cannot find this code on your github. which repository is it in?
Could you go deeper and build a custom strategy with custom data without using examples in the official tutorial?
For the people reading this:
You can create your own CSV's, they just have to have the same format as the one in the example. For example you can obtain historic data via the Binance API and then reformat it to match the format of this CSV and then just use it like shown here.
I have done a number of videos since this one where I use backtrader (this was my first exposure). Check out the last video of the full stack tutorial where I backtest Opening Range Breakout, for instance.
Larry, once again, your tutorial has helped me greatly. This information is absolute gold and you're going to make me very rich :P. I'll be sure to send you some bitcoin if it all works out. Your channel is under appreciated. You turned a subject that is difficult to understand/dry, into something clear, easy and fun. Thank you.
Thanks so much! I took a break these past few weeks, but much more to come.
Hello, Larry! I've tried a few times to find this file on your github but did not find it. Could you please give me the link?
I don't understand how the print(self.order) thing works or should work - from what I see, self.order is simply assigned None so I don't see how it could print as anything other than None (which is what it does for me). Any clues please?
Same problem
@@pavloruzanov682 add self.order = self.buy() in the last line of the next function
is source code on github, followed link cant find it
(i see from previous links you have not bother to upload source, shame as it is giving errors on PyCharm. Actual source may solve this)
IF you have problems with ploting at VSCode, try to install matplotlib==3.2.2, it should work!
The markers on the plot seem misplaced to me. For example, the 5th buy and sell. The blue/red indicator at the top indicates this sell was a loss, but the green/red markers below make it appear to be a gain (inspecting the numbers in the log confirms it was actually a loss). Is this just a "feature" of matplotlib?
Great series of videos - your voice over makes it so much easier to understand the code. Coding quickly and effortlessly on camera like this with so few errors demonstrates strong coding skills.
This is a super well explained video. Looking forward to the next one!
Thanks man, I appreciate hearing that so much. Definitely planning to do more, it is motivating to hear these are useful. More to come. Thanks for watching.
@@parttimelarry would really like some more videos in your style on other strategies + connecting to robin_stocks API for example and placing orders. your logic looks sound definitely should be able to bring in real returns.
@@parttimelarry Did you ever finish the series and implement with alpaca?
I have been going over backtrader and love your approach to explaining it . Seeing more backtrader strategies would be super helpful too, thanks :)
Thanks for this awesome tutorial
cant find the source code for this.
Hey, Thanks Larry.. Awesome I coded all worked as you explained including TDA streaming(your other video). One question: how to integrate Backtrader functionality code (back tested strategy class) directly in the other TDAmeritade streaming example with less modifications. Other words leverage all functionalities(indicators & order stack/array) instead of building my own logic.? Appreciate your help.
I think you are asking about Backtrader live trading right? I actually haven't tried it yet, but I should. Added it to my list.
@@parttimelarry Yes, thats correct. Pls make one simple example with TD-Ameritrade broker(streaming) and back-trader strategy class(how to promote from back testing to real prod environment). Thanks again for adding the request.
Can you post the completed code somewhere?
why do I get :
SELL CREATED
everything works great. but couldnt get it to display a chart.
right after final portfolio value =1017520.00
[[Figure size 432 x 288 with 4 axes>]]
do i half to tell it what the screensize should be?
Many thanks for taking the time to create these informative videos
Man!!! This is a great content!! Awesome! Hug from brasil
I can't visualize the data, because I get an error:
"RuntimeError: The current Numpy installation
fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: tinyurl.com/y3dm3h86
"
Hi
I've been going through your binance API tutorial , now just going through the backtesting videos in detail before finishing the binance API and starting implementing my strategies.
Your channel is great and this is a euphemism, your teaching method is spot on, you focus on the important information but there's just enough in what you say, search or with what's on the screen to help me search for additional information I miss (install additional modules, etc.). I'm a beginner crypto trader, if I can really call myself a trader, and I'm poor programmer, but with your help I feel I can really progress. Not expecting to get rich but at least I'm understanding a lot more and it gives me key entry points to keep learning, whether it's about programming or technical analysis, or the exchange markets in general. Fascinating stuff.
This is brilliant ! Thank you.
2024 this was so awesome bro thans alot wished you could explain some of the codes any way tnx
anyone else having trouble with the execution ? The code is correct, but the Buy and Sell orders aren't being executed :/
Thanks for making such a video! It's really helpful!!!
my bot doesnt enter any trades, any recommendations ?
class TestStrategy3(bt.Strategy):
def log(self, txt, dt=None):
''' Logging function for this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
self.order = None
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY EXECUTED {}'.format(order.executed.price))
elif order.issell():
self.log('SELL EXECUTED {}'.format(order.executed.price))
self.bar_executed = len(self)
# Write down: no pending order
self.order = None
def next(self):
self.log('Close, %.2f' % self.dataclose[0])
if self.order:
return
if not self.position:
print(len(self))
print(self.order)
print(self.position)
if self.dataclose[0] < self.dataclose[-1]:
if self.dataclose[-1] < self.dataclose[-2]:
self.log('BUY CREATE, %.2f' % self.dataclose[0])
self.order = self.buy()
else:
if len(self) >= (self.bar_executed + 5):
self.log('SELL CREATED {}'.format(self.dataclose[0]))
self.order = self.sell()
you should have mentioned a specific github code path instead of giving your list of repositories. how can one identify the code from your repository?
Thanks. Very useful and nicely explained. I tried to follow the BT quickstart guide initially but this made it easier to understand. Would like to wait more videos on strategies tested on backtrader.
good vids but this one is not too helpful. you make it up on the fly with little discussion of why, or where the commands are coming from. a diagram to start and then discussion of where new commands are coming from is necessary. otherwise this video is only for experts and experts do not need your help.
subscribed, amazing videos and clear explanation. Looking forward to more backtrader videos
Thank you, the was really helpful. I wish I knew this library before
Looking forward to the next one, when do you plan to make this?
Thanks for sharing, great videos with nice explanation!!
you are legend man, please keep doing what are you doing.
Up to this video for today. ^^
See you soon.
Really nice content. You should continue with the serie.
greetings.Great job .It explains a lots
Thanks Larry. This is awsome method to test trading strategy
This does not work for me. cerebro.plot()
I got this error: AttributeError: _axes
How can I fix it?
you find solution
Time Stamp 8:07 Larry, I don't know if I need glasses or if you need glasses or I am just WRONG, but at the above timestamp you are saying that you only made $17.52. Ok, again, I could be wrong but it looks to me you made more like $808,017.52
Please confirm. If you made this, I would like to revisit this strategy and dive into what it is doing. Thanks, lol This is unbelievable. Also, If you can illustrate how to pull data for multiple currency pairs with multiple time intervals for analysis. Without multiple time intervals (S5, S30, M1, M3, M5), of course it's a waste of time. Would be much better off doing trading off the port folio of the company and trading long term, but for scalping we need all the time intervals aligned like a tsunami.
Hi again ,
I have here few questions....
Question 1 :
BUY CREATED & BUY EXECUTED --> Why do they have a different price ?
SELL CREATED & SELL EXECUTED --> Why do they have a different price ?
ASSUMED ANSWER :Is it because the stock is not available immediately for both orders ?
Question 2 :
Why I want to grab multiple csv files from local machine but i managed with a one line code with python to put them all in one variable .
How to include this variable containing all my data in Backtrader ? (again from my local machine and not yahoofinance ....)
Thank you
Hi Larry thanks a lot for sharing these precious tutorials.. I have 1 issue if you can help me please.. I developed a trading system with Backtrader but I want it to execute ONLY 1 trade per day.. How is this possible please? Thank you in advance
I noticed your orders are executing a day after the trigger. That is also happening with my code. Any suggestions? Also, some of my orders aren't executing at all..
Hi!
I'm have a little problem, I did everything just as you said and for some reason my orser.status keeps going to Margin(7), do you know why this could happen?
You talked about taking the strategy live, but I can't find that video? Did that happen somewhere?
Thanks!
1000 shares @ ~$25 / share = $25k .. n a final p/l +$17k is actually really good. thx for the video
One more subscriber. Thanks for making things "easier" for us. Keep it up
how to get those values in the tabular formal of buy created and sell created
can you explain how to add another data feed like binance coinbase etc
Do you prove your algo in real time?
Great! Isn't possible to connect to IB?
Can you make a video on backtrader interactive brokers capability with some real life example of algo execution of a strategy?
Hi thanks, signing up for interactive brokers so I can check it out. Will do a series on it.
I really enjoy backtrader, so glad that I discovered it through this video! Before, I was trying to get zipline up and running, it is also a very good package. Backtrader is much more user-friendly however, and still offers more than enough functionality :) thanks for the video, thumbs up
Please help me solve this error:
Traceback (most recent call last):
File "C:\Users\Anish\AppData\Local\Programs\Python\Python37\backtrad3.py", line 3, in
from srat import TestStrategy
File "C:\Users\Anish\AppData\Local\Programs\Python\Python37\srat.py", line 4, in
class TestStrategy(backtrader.Strategy):
File "C:\Users\Anish\AppData\Local\Programs\Python\Python37\srat.py", line 58, in TestStrategy
cerebro.addsizer(FixedReverser)
NameError: name 'cerebro' is not defined