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

Комментарии • 70

  • @parttimelarry
    @parttimelarry  4 года назад +2

    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

  • @JohnDoe-vo6uf
    @JohnDoe-vo6uf 3 года назад +5

    i cannot find this code on your github. which repository is it in?

  • @jc_777
    @jc_777 4 года назад +26

    Could you go deeper and build a custom strategy with custom data without using examples in the official tutorial?

    • @justanotherguycalledchris7297
      @justanotherguycalledchris7297 3 года назад

      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.

    • @parttimelarry
      @parttimelarry  3 года назад +6

      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.

  • @syproductions456
    @syproductions456 4 года назад +17

    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.

    • @parttimelarry
      @parttimelarry  4 года назад +3

      Thanks so much! I took a break these past few weeks, but much more to come.

  • @vladimirsaraikin6888
    @vladimirsaraikin6888 3 года назад +3

    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?

  • @BorrowedAtoms
    @BorrowedAtoms 3 года назад +3

    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?

    • @pavloruzanov682
      @pavloruzanov682 3 года назад

      Same problem

    • @Hutspotpwns
      @Hutspotpwns 2 года назад

      ​@@pavloruzanov682 add self.order = self.buy() in the last line of the next function

  • @wilamshields
    @wilamshields 3 года назад +1

    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)

  • @andref9639
    @andref9639 3 года назад +1

    IF you have problems with ploting at VSCode, try to install matplotlib==3.2.2, it should work!

  • @MartyBower
    @MartyBower Год назад +1

    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.

  • @sayakbhattacharyyakf
    @sayakbhattacharyyakf 4 года назад +9

    This is a super well explained video. Looking forward to the next one!

    • @parttimelarry
      @parttimelarry  4 года назад +3

      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.

    • @sayakbhattacharyyakf
      @sayakbhattacharyyakf 4 года назад

      @@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.

    • @wglind
      @wglind 4 года назад

      @@parttimelarry Did you ever finish the series and implement with alpaca?

  • @upperlower3889
    @upperlower3889 4 года назад +4

    I have been going over backtrader and love your approach to explaining it . Seeing more backtrader strategies would be super helpful too, thanks :)

  • @melsaied101
    @melsaied101 Год назад +1

    Thanks for this awesome tutorial

  • @akshayparate9362
    @akshayparate9362 3 года назад +1

    cant find the source code for this.

  • @arcsha2336
    @arcsha2336 4 года назад +2

    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.

    • @parttimelarry
      @parttimelarry  4 года назад +1

      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.

    • @arcsha2336
      @arcsha2336 4 года назад

      @@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.

  • @Pvsmuntje
    @Pvsmuntje 4 года назад +2

    Can you post the completed code somewhere?

  • @NurburgringTrack
    @NurburgringTrack 4 года назад

    why do I get :
    SELL CREATED

  • @rverm1000
    @rverm1000 4 года назад +1

    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?

  • @flydr2
    @flydr2 2 года назад +1

    Many thanks for taking the time to create these informative videos

  • @luizfernandolopes
    @luizfernandolopes 4 года назад +2

    Man!!! This is a great content!! Awesome! Hug from brasil

  • @pestibotond6841
    @pestibotond6841 3 года назад

    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
    "

  • @nicolaschataignon6201
    @nicolaschataignon6201 3 года назад +1

    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.

  • @ahmedbadal3795
    @ahmedbadal3795 3 месяца назад

    2024 this was so awesome bro thans alot wished you could explain some of the codes any way tnx

  • @ahmedzaoui9130
    @ahmedzaoui9130 Год назад

    anyone else having trouble with the execution ? The code is correct, but the Buy and Sell orders aren't being executed :/

  • @rui3767
    @rui3767 4 года назад +1

    Thanks for making such a video! It's really helpful!!!

  • @zaferatakan1082
    @zaferatakan1082 3 года назад

    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()

  • @manojmahanty8830
    @manojmahanty8830 2 года назад

    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?

  • @sushilkv2004
    @sushilkv2004 4 года назад +1

    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.

  • @dfage33
    @dfage33 2 года назад

    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.

  • @tommyypoon
    @tommyypoon 4 года назад +1

    subscribed, amazing videos and clear explanation. Looking forward to more backtrader videos

  • @80amnesia
    @80amnesia 4 года назад +1

    Thank you, the was really helpful. I wish I knew this library before

  • @josephastrahan6403
    @josephastrahan6403 4 года назад +1

    Looking forward to the next one, when do you plan to make this?

  • @smjure
    @smjure 4 года назад +1

    Thanks for sharing, great videos with nice explanation!!

  • @moodz9217
    @moodz9217 4 года назад +1

    you are legend man, please keep doing what are you doing.

  • @cjfeat.2631
    @cjfeat.2631 3 года назад +1

    Up to this video for today. ^^
    See you soon.

  • @Zauoyds
    @Zauoyds 4 года назад +1

    Really nice content. You should continue with the serie.

  • @maciekpaciarski9343
    @maciekpaciarski9343 4 года назад +1

    greetings.Great job .It explains a lots

  • @hpssskkk
    @hpssskkk 4 года назад +1

    Thanks Larry. This is awsome method to test trading strategy

  • @ploleo
    @ploleo Год назад

    This does not work for me. cerebro.plot()
    I got this error: AttributeError: _axes
    How can I fix it?

  • @SolidBuildersInc
    @SolidBuildersInc 3 года назад

    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.

  • @ihebbibani7122
    @ihebbibani7122 3 года назад

    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

  • @futurestadawul
    @futurestadawul 2 года назад

    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

  • @zeromodz
    @zeromodz 3 года назад

    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..

  • @dorkokotek4872
    @dorkokotek4872 3 года назад

    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?

  • @brianrowe1152
    @brianrowe1152 3 года назад

    You talked about taking the strategy live, but I can't find that video? Did that happen somewhere?
    Thanks!

  • @adamderose9468
    @adamderose9468 3 года назад

    1000 shares @ ~$25 / share = $25k .. n a final p/l +$17k is actually really good. thx for the video

  • @ihebbibani7122
    @ihebbibani7122 3 года назад

    One more subscriber. Thanks for making things "easier" for us. Keep it up

  • @srivindhya950
    @srivindhya950 4 года назад

    how to get those values in the tabular formal of buy created and sell created

  • @moodz9217
    @moodz9217 4 года назад

    can you explain how to add another data feed like binance coinbase etc

  • @sunday-thequant8477
    @sunday-thequant8477 4 года назад

    Do you prove your algo in real time?

  • @thomas2004ch
    @thomas2004ch 3 года назад

    Great! Isn't possible to connect to IB?

  • @kannansingaravelu
    @kannansingaravelu 4 года назад

    Can you make a video on backtrader interactive brokers capability with some real life example of algo execution of a strategy?

    • @parttimelarry
      @parttimelarry  4 года назад +1

      Hi thanks, signing up for interactive brokers so I can check it out. Will do a series on it.

  • @CR-er6pi
    @CR-er6pi 4 года назад +1

    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

  • @anish_19099
    @anish_19099 3 года назад

    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