Close Menu
    Trending
    • Google, Spotify Down in a Massive Outage Affecting Thousands
    • Prediksi Kualitas Anggur dengan Random Forest — Panduan Lengkap dengan Python | by Gilang Andhika | Jun, 2025
    • How a 12-Year-Old’s Side Hustle Makes Nearly $50,000 a Month
    • Boost Your LLM Output and Design Smarter Prompts: Real Tricks from an AI Engineer’s Toolbox
    • Proposed Study: Integrating Emotional Resonance Theory into AI : An Endocept-Driven Architecture | by Tim St Louis | Jun, 2025
    • What’s the Highest Paid Hourly Position at Walmart?
    • Connecting the Dots for Better Movie Recommendations
    • Diabetes Prediction with Machine Learning by Model Mavericks | by Olivia Godwin | 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

    Prediksi Kualitas Anggur dengan Random Forest — Panduan Lengkap dengan Python | by Gilang Andhika | Jun, 2025

    June 13, 2025
    Machine Learning

    Proposed Study: Integrating Emotional Resonance Theory into AI : An Endocept-Driven Architecture | by Tim St Louis | Jun, 2025

    June 13, 2025
    Machine Learning

    Diabetes Prediction with Machine Learning by Model Mavericks | by Olivia Godwin | Jun, 2025

    June 12, 2025
    Add A Comment

    Comments are closed.

    Top Posts

    How Microsoft Power BI Elevated My Data Analysis and Visualization Workflow

    May 28, 2025

    Compression Algorithms: How To Zip Files & Save Space | by AirLab Media | Apr, 2025

    April 6, 2025

    AI in Prostate Cancer Imaging: Current Trends

    March 12, 2025

    The $50 Software That Could Save Your Business One Day

    April 17, 2025

    Feel Like Your Business Is Destined to Stay Small? Here’s How to Unlock Explosive Growth.

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

    Diffusion Models, Explained Simply | Towards Data Science

    May 6, 2025

    Understanding Retrieval Augmented Generation (RAG): Conceptual Overview | by Dr. Sumedh Kanade | kanade/dev | Feb, 2025

    February 9, 2025

    Amplifying Creativity: Building an AI-Powered Content Creation Assistant — Part 3 | by Markell Richards | Apr, 2025

    April 7, 2025
    Our Picks

    Technology is NOT Making Humans Stupid: But Fear and Laziness Might. | by Allison Binger | Apr, 2025

    April 1, 2025

    Diversify Revenue Streams for Your Business in This Candlestick Trading Masterclass

    April 3, 2025

    5 Trends Influencing the Future of Ecommerce

    March 6, 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.