Close Menu
    Trending
    • High Paying, Six Figure Jobs For Recent Graduates: Report
    • What If I had AI in 2018: Rent the Runway Fulfillment Center Optimization
    • YouBot: Understanding YouTube Comments and Chatting Intelligently — An Engineer’s Perspective | by Sercan Teyhani | Jun, 2025
    • Inspiring Quotes From Brian Wilson of The Beach Boys
    • AI Is Not a Black Box (Relatively Speaking)
    • From Accidents to Actuarial Accuracy: The Role of Assumption Validation in Insurance Claim Amount Prediction Using Linear Regression | by Ved Prakash | Jun, 2025
    • I Wish Every Entrepreneur Had a Dad Like Mine — Here’s Why
    • Why You’re Still Coding AI Manually: Build a GPT-Backed API with Spring Boot in 30 Minutes | by CodeWithUs | Jun, 2025
    Finance StarGate
    • Home
    • Artificial Intelligence
    • AI Technology
    • Data Science
    • Machine Learning
    • Finance
    • Passive Income
    Finance StarGate
    Home»Machine Learning»Building a Stock Trading Model Using Artificial Neural Networks (ANN) with Backtrader with the help of ChatGPT | by Cosmin | Mar, 2025
    Machine Learning

    Building a Stock Trading Model Using Artificial Neural Networks (ANN) with Backtrader with the help of ChatGPT | by Cosmin | Mar, 2025

    FinanceStarGateBy FinanceStarGateMarch 13, 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In recent times, know-how and knowledge evaluation have revolutionized the monetary markets, and using synthetic intelligence in buying and selling has develop into more and more in style. Probably the most fundamental instruments for creating an automatic buying and selling system is utilizing synthetic neural networks (ANN). On this article, I’ll stroll you thru how I applied a easy neural community mannequin for inventory buying and selling utilizing Backtrader — a Python library for backtesting buying and selling methods.

    The objective of this undertaking was to construct an automated buying and selling system that makes use of a neural community mannequin to investigate historic buying and selling knowledge and predict whether or not the worth of a monetary asset will go up or down over a particular time interval. Moreover, this mannequin makes purchase or promote choices based mostly on its predictions.

    For this undertaking, I selected the next instruments and libraries:

    • Backtrader: A Python library that lets you construct, check, and implement buying and selling methods.
    • TensorFlow and Keras: To construct and prepare the neural community.

    Backtrader helps us construct buying and selling methods and check them on historic knowledge, whereas TensorFlow/Keras are used to create the neural community that can predict the path of the asset’s worth.

    The info used to coach the neural community was taken from a monetary market, and every line within the dataset comprises the next data:

    • Date and time (e.g., 2025-03-06 14:30:00)
    • Opening worth (Open)
    • Excessive worth (Excessive)
    • Low worth (Low)
    • Closing worth (Shut)
    • Quantity traded (Quantity)

    This knowledge is important for market evaluation and for constructing a mannequin that may predict market actions based mostly on earlier worth motion.

    The neural community I constructed is kind of easy, consisting of a number of dense layers with ReLU and Tanh activation capabilities to foretell market path.

    class ANNStrategy(bt.Technique):
    def __init__(self):
    self.mannequin = self.build_model()
    self.data_list = []

    def build_model(self):
    mannequin = Sequential([
    Dense(64, activation='relu', input_shape=(5,)),
    Dense(32, activation='relu'),
    Dense(1, activation='tanh')
    ])
    mannequin.compile(optimizer='adam', loss='mse')
    return mannequin

    On this neural community:

    • The enter is a vector consisting of 5 options:
    • The closing worth and quantity for the final 3 durations.
    • The output is a price between -1 and 1, indicating the market prediction:
    • A constructive worth indicators a purchase advice.
    • A adverse worth indicators a promote advice.

    To coach the neural community, I used historic buying and selling knowledge. At every step, I used the final 3 durations of knowledge to create an enter vector for the community. The mannequin was then skilled on the entire dataset to regulate its parameters and make extra correct predictions.

    if len(self.data_list) > 100:
    X_train = np.array(self.data_list[:-1])
    y_train = np.array([1 if f[2] > f[4] else -1 for f in self.data_list[1:]])
    self.mannequin.match(X_train, y_train, epochs=5, verbose=0)

    Because the neural community makes predictions concerning the market’s actions, our algorithm decides whether or not to purchase or promote an asset based mostly on these predictions. The choice-making course of seems one thing like this:

    prediction = self.mannequin.predict(np.array([features]))[0][0]
    if prediction > 0.5:
    self.purchase()
    elif prediction self.promote()

    If the mannequin predicts a worth improve (i.e., a price higher than 0.5), it’s going to purchase the asset. If the mannequin predicts a worth lower (i.e., a price lower than -0.5), it’s going to promote the asset.

    As soon as the neural community and buying and selling technique have been applied, I ran the backtest utilizing Backtrader. This allowed me to simulate how the buying and selling technique would carry out on historic knowledge with out risking actual cash.

    cerebro = bt.Cerebro()
    knowledge = bt.feeds.GenericCSVData(
    dataname="market_data.csv",
    dtformat="%Y-%m-%d %H:%M:%S", # Guarantee appropriate date format
    timeframe=bt.TimeFrame.Minutes,
    compression=1,
    openinterest=-1 # Set to -1 in case your dataset doesn’t have this column
    )
    cerebro.adddata(knowledge)
    cerebro.addstrategy(ANNStrategy)
    cerebro.run()
    cerebro.plot()

    This may show the outcomes of the backtest and plot the efficiency of the technique, permitting you to evaluate how properly the mannequin would have carried out previously.

    That is the plot that the ANN produced, not fairly a transparent picture

    Constructing a inventory buying and selling mannequin utilizing synthetic neural networks (ANN) with Backtrader has been an thrilling journey into the world of algorithmic buying and selling. By leveraging the facility of deep studying, I used to be in a position to create a system able to analyzing historic worth knowledge and making buying and selling choices robotically.

    This undertaking is only the start. With extra superior methods and bigger datasets, I plan to proceed enhancing the mannequin, including extra options (e.g., technical indicators) and optimizing the structure for higher efficiency. Sooner or later, I hope to discover completely different fashions, akin to recurrent neural networks (RNN), which may very well be notably efficient for time sequence forecasting in buying and selling.

    Should you’re keen on monetary markets and machine studying, this undertaking gives an excellent introduction to the world of algorithmic buying and selling. Joyful coding!



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMost Canadians feel tips are too high: survey
    Next Article How to Own a Franchise As a Side Hustle
    FinanceStarGate

    Related Posts

    Machine Learning

    YouBot: Understanding YouTube Comments and Chatting Intelligently — An Engineer’s Perspective | by Sercan Teyhani | Jun, 2025

    June 13, 2025
    Machine Learning

    From Accidents to Actuarial Accuracy: The Role of Assumption Validation in Insurance Claim Amount Prediction Using Linear Regression | by Ved Prakash | Jun, 2025

    June 13, 2025
    Machine Learning

    Why You’re Still Coding AI Manually: Build a GPT-Backed API with Spring Boot in 30 Minutes | by CodeWithUs | Jun, 2025

    June 13, 2025
    Add A Comment

    Comments are closed.

    Top Posts

    AI-Powered Customer Insights: Understanding Your Audience for Better Branding by Daniel Reitberg – Daniel David Reitberg

    March 6, 2025

    FedEx Deploys Hellebrekers Robotic Sorting Arm in Germany

    June 13, 2025

    A 5 Step Guide to Smarter Business Growth

    April 25, 2025

    Multi-Agent Communication with the A2A Python SDK

    May 28, 2025

    Generative AI Made Simple: How Neural Networks Create Text, Images, and More

    April 28, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Data Science
    • Finance
    • Machine Learning
    • Passive Income
    Most Popular

    Expert AI and Machine Learning Dissertation Writing and Coding Services for UK Students | by Tutorsindia | May, 2025

    May 8, 2025

    Why So Many Business Owners Use MacBooks

    March 17, 2025

    AI is pushing the limits of the physical world

    April 21, 2025
    Our Picks

    Teen With Cerebral Palsy Starts Business Making $5M a Year

    March 19, 2025

    Autoencoder LSTM aplicado ao Dataset 3W | by mvittoriasl | Apr, 2025

    April 2, 2025

    Most Crowded AI ML Institute You’ll Find In Bangalore? | by Mohammed Numan | May, 2025

    May 30, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Data Science
    • Finance
    • Machine Learning
    • Passive Income
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 Financestargate.com All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.