惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Latest news
Latest news
T
Troy Hunt's Blog
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
V
V2EX
博客园 - 司徒正美
B
Blog RSS Feed
AWS News Blog
AWS News Blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI
NISL@THU
NISL@THU
博客园 - Franky
P
Proofpoint News Feed
博客园_首页
C
CERT Recently Published Vulnerability Notes
雷峰网
雷峰网
S
Schneier on Security
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
G
GRAHAM CLULEY
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
WordPress大学
WordPress大学
The Hacker News
The Hacker News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
T
The Exploit Database - CXSecurity.com
Engineering at Meta
Engineering at Meta
罗磊的独立博客
T
The Blog of Author Tim Ferriss
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
SecWiki News
SecWiki News
云风的 BLOG
云风的 BLOG
美团技术团队
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
B
Blog
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Stock Market Trading Bot in Python: My Neo Moment
Timevolt · 2026-06-22 · via DEV Community

Timevolt

The Quest Begins (The "Why")

Honestly, I was tired of watching my portfolio fluctuate while I stared at candlestick charts like they were hieroglyphics. I’d read a few blog posts about algorithmic trading, copy‑pasted some snippets, and ended up with a script that either did nothing or blew up my virtual account in a flash. It felt like trying to defeat a final boss without knowing its attack pattern—frustrating and a little embarrassing.

One rainy Saturday, after yet another “why isn’t this working?” moment, I realized the problem wasn’t the idea; it was the foundation. I was mixing data fetching, signal generation, and order execution in a single messy script, and every tiny change broke something else. I needed a clean separation of concerns, a solid backtesting loop, and a way to visualize what the bot was actually doing. That’s when the quest truly started: build a simple but extensible trading bot that I could understand, tweak, and trust.

The Revelation (The Insight)

The big “aha!” came when I treated the bot like a mini‑operating system: three independent modules talking through well‑defined interfaces.

  1. Data Layer – pulls market data (price, volume, maybe fundamentals) and stores it in a pandas DataFrame.
  2. Strategy Layer – receives that DataFrame, computes indicators, and returns a signal (-1, 0, or 1).
  3. Execution Layer – takes the signal, checks risk limits, and sends an order to a broker API (or a paper‑trading simulator).

Why does this matter? Because now I can swap out the strategy without touching the data fetcher, or test a new execution logic with historical data alone. It’s like having interchangeable armor pieces—you can upgrade your sword without reforging the whole suit.

The revelation also taught me to respect state. A bot isn’t a stateless function; it needs to remember its position, open orders, and the timestamp of the last bar it processed. Keeping that state in a simple class made debugging a breeze and prevented the dreaded “double‑buy” bug that once turned my paper profit into a loss.

Wielding the Power (Code & Examples)

The Struggle – A Monolithic Mess

# 🚫 Don't do this – everything tangled together
import yfinance as yf
import ta

def run_bot():
    data = yf.download("AAPL", period="60d", interval="1h")
    data["rsi"] = ta.momentum.RSIIndicator(data["Close"]).rsi()
    data["signal"] = 0
    data.loc[data["rsi"] < 30, "signal"] = 1   # buy
    data.loc[data["rsi"] > 70, "signal"] = -1  # sell

    position = 0
    for idx, row in data.iterrows():
        if row["signal"] == 1 and position == 0:
            print(f"BUY at {row['Close']}")
            position = 1
        elif row["signal"] == -1 and position == 1:
            print(f"SELL at {row['Close']}")
            position = 0

Problems:

  • Data fetching, indicator calc, signal logic, and order simulation are all in one function.
  • No clear way to test the strategy independently.
  • Hard to change the broker or add risk management without rewriting loops.

The Victory – Clean, Modular Design

First, let’s define a tiny data container that any layer can consume:

import pandas as pd

class MarketData:
    def __init__(self, df: pd.DataFrame):
        self.df = df.copy()   # we’ll work on a copy to avoid side‑effects

Data Layer – fetching OHLCV

import yfinance as yf

def fetch_data(symbol: str, period: str = "60d", interval: str = "1h") -> MarketData:
    raw = yf.download(symbol, period=period, interval=interval)
    # Keep only needed columns and drop NaNs
    raw = raw[["Open", "High", "Low", "Close", "Volume"]].dropna()
    return MarketData(raw)

Strategy Layer – plug‑and‑play signals

import ta

def rsi_strategy(data: MarketData, oversold: int = 30, overbought: int = 70) -> pd.Series:
    close = data.df["Close"]
    rsi = ta.momentum.RSIIndicator(close).rsi()
    signal = pd.Series(0, index=close.index)
    signal[rsi < oversold] = 1   # buy
    signal[rsi > overbought] = -1 # sell
    return signal

Notice how the strategy only cares about a MarketData object and returns a pure pandas Series. Unit‑testing this function is now trivial—just feed it a fabricated DataFrame.

Execution Layer – paper trading with risk checks

class PaperExecutor:
    def __init__(self, initial_cash: float = 10_000):
        self.cash = initial_cash
        self.position = 0          # number of shares held
        self.trades = []           # log for later analysis

    def execute(self, data: MarketData, signal: pd.Series):
        """Iterate bar‑by‑bar, place orders according to signal."""
        for ts, row in data.df.iterrows():
            price = row["Close"]
            sig = signal.loc[ts]

            if sig == 1 and self.position == 0:          # buy signal, flat
                shares = int(self.cash // price)          # simple sizing
                if shares > 0:
                    self.cash -= shares * price
                    self.position += shares
                    self.trades.append((ts, "BUY", shares, price))
                    print(f"{ts}: BUY {shares} @ {price:.2f}")

            elif sig == -1 and self.position > 0:        # sell signal, long
                self.cash += self.position * price
                self.trades.append((ts, "SELL", self.position, price))
                print(f"{ts}: SELL {self.position} @ {price:.2f}")
                self.position = 0

        # liquidate any remaining position at the close of the data
        if self.position > 0:
            final_price = data.df.iloc[-1]["Close"]
            self.cash += self.position * final_price
            self.trades.append((data.df.index[-1], "SELL", self.position, final_price))
            print(f"Liquidated {self.position} shares at {final_price:.2f}")

    def summary(self):
        print(f"\nFinal cash: ${self.cash:,.2f}")
        print(f"Number of trades: {len(self.trades)//2}")  # BUY+SELL pair

Wiring it all together – the “main” quest loop

if __name__ == "__main__":
    # 1️⃣ Get data
    market = fetch_data("AAPL")

    # 2️⃣ Generate signal
    sig = rsi_strategy(market)

    # 3️⃣ Execute trades
    broker = PaperExecutor(initial_cash=20_000)
    broker.execute(market, sig)

    # 4️⃣ Review results
    broker.summary()

What changed?

  • Each block has a single responsibility.
  • I can replace rsi_strategy with a moving‑average crossover, a machine‑learning model, or even a sentiment‑based signal without touching the fetcher or executor.
  • The PaperExecutor class encapsulates cash, position, and trade logging—no global state leaking everywhere.
  • Adding a stop‑loss or position‑size rule is now a few lines inside execute.

Common Traps to Avoid (The “Boss Mechanics”)

  1. Look‑ahead bias – Never use future data to compute a signal. In the example, the RSI is calculated purely from historical closes up to the current bar. If you accidentally shift the signal forward (signal.shift(-1)) you’ll think you’ve invented a money‑printing machine—until you go live and watch your account evaporate.

  2. Over‑fitting to historical noise – It’s tempting to tweak oversold/overbought until the backtest shows a 200% return. Remember, the market isn’t a puzzle you can solve by brute‑forcing parameters. Use walk‑forward validation or keep a strict out‑of‑sample test period. I once spent three hours optimizing thresholds on six months of data, only to see the bot lose money the very next week—classic boss‑level humility check.

Why This New Power Matters

Now that the bot’s architecture is clean, you can experiment fearlessly. Want to try a pairs‑trading strategy? Write a new function that takes two MarketData objects and returns a spread signal. Curious about integrating news sentiment? Pull in a dataframe of headlines, compute a score, and feed it into your strategy layer—no need to rewrite the execution engine.

More importantly, you’ve got a framework for learning. Each tweak teaches you something about market mechanics, risk management, or the quirks of your chosen broker’s API. The excitement of seeing your bot make its first profitable trade (even in paper) feels like finally landing that perfect combo in a fighting game—your heart races, you grin, and you instantly want to push further.

And the best part? You’re not just building a toy; you’re laying the groundwork for something that could evolve into a live trading system, a research platform, or even a teaching tool for friends who want to dip their toes into quant finance.

Your Turn – The Next Quest

Grab your favorite symbol, swap in a different indicator (MACD, Bollinger Bands, or even a simple moving‑average crossover), and see how the equity curve changes. Try adding a fixed fractional position‑size rule inside PaperExecutor.execute and watch how risk management smooths out the ride.

What strategy are you itching to test first? Drop your ideas in the comments—I’d love to hear about the next boss you’re planning to defeat! 🚀