xiaohongshu
xiaohongshu
finwiz-security
Security and type safety standards for FinWiz including API key management, input validation, and mypy strict mode. Use when handling sensitive data, API keys, or implementing type safety.
Full skill instructions
Critical security practices and type safety requirements for FinWiz development.
All public functions and methods MUST have complete type annotations:
# ✅ CORRECT
def analyze_stock(ticker: str, period: int = 365) -> StockAnalysis:
return StockAnalysis(ticker=ticker, period=period)
def log_analysis(ticker: str) -> None:
logger.info(f"Analyzing {ticker}")
# ❌ WRONG - Missing return type
def analyze_stock(ticker: str):
return StockAnalysis(ticker=ticker)
-> None if no return)str | None instead of Optional[str]list[Type] instead of List[Type]# type: ignore only with explanatory commentNEVER hardcode API keys:
# ✅ CORRECT
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable not set")
# ❌ WRONG - Hardcoded
api_key = "sk-proj-abc123..."
Core APIs (Required):
OPENAI_API_KEY - OpenAI APISERPER_API_KEY - Serper searchFIRECRAWL_API_KEY - Web scrapingALPHA_VANTAGE_API_KEY - Financial dataEnhanced Features (Optional):
TWELVE_DATA_API_KEY - Market data (technical analysis)PPLX_API_KEY - Perplexity search (enhanced research)SEC_API_API_KEY - SEC filings (optional)CHART_IMG_API_KEY - Chart generationCOINMARKETCAP_API_KEY - Cryptocurrency dataNEVER log full API keys:
# ✅ CORRECT - Masked (first 8 chars only)
logger.info(f"Using API key: {api_key[:8]}...")
# ❌ WRONG - Full key exposed
logger.info(f"API key: {api_key}")
from pydantic import BaseModel, Field, field_validator
class TickerInput(BaseModel):
"""Validate ticker input with strict security."""
model_config = {
"str_strip_whitespace": True,
"str_upper": True,
"extra": "forbid" # Reject unknown fields
}
symbol: str = Field(..., pattern=r'^[A-Z]{1,5}$')
@field_validator('symbol')
@classmethod
def validate_ticker(cls, v: str) -> str:
if not v.isalpha():
raise ValueError('Ticker must contain only letters')
return v.upper()
extra='forbid' - Reject unknown fieldsField() constraints - pattern, min_length, ge, le@field_validator - Complex validation logic# ✅ CORRECT - Anonymized
logger.info(f"Analyzing portfolio with {len(holdings)} holdings")
# ❌ WRONG - Exposes personal data
logger.info(f"Analyzing portfolio: {holdings}")
Generic to users, detailed internally:
# ✅ CORRECT
try:
result = api_call(ticker)
except Exception as e:
logger.error(f"API call failed for {ticker}: {e}", exc_info=True)
raise ValueError("Unable to fetch data. Please try again later.")
# ❌ WRONG - Exposes internals
except Exception as e:
raise ValueError(f"API call to {api_url} failed: {e}")
from finwiz.utils.rate_limiter import RateLimiter
limiter = RateLimiter(max_calls=20, period=60)
@limiter.limit
async def fetch_stock_data(ticker: str) -> dict:
return await api_client.get(f"/stock/{ticker}")
Always set explicit timeouts:
# ✅ CORRECT
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url)
# ❌ WRONG - Can hang indefinitely
async with httpx.AsyncClient() as client:
response = await client.get(url)
# ✅ CORRECT - Parameterized queries
cursor.execute(
"SELECT * FROM stocks WHERE ticker = %s",
(ticker,)
)
# ❌ WRONG - SQL injection risk
cursor.execute(f"SELECT * FROM stocks WHERE ticker = '{ticker}'")
from pathlib import Path
# ✅ CORRECT - Validate paths
def read_report(filename: str) -> str:
# Validate filename
if not filename.replace('-', '').replace('_', '').isalnum():
raise ValueError("Invalid filename")
# Resolve path safely
base_path = Path("reports")
file_path = (base_path / filename).resolve()
# Ensure path is within base directory
if not str(file_path).startswith(str(base_path.resolve())):
raise ValueError("Path traversal attempt")
return file_path.read_text()
# ❌ WRONG - Path traversal risk
def read_report(filename: str) -> str:
with open(f"reports/{filename}") as f:
return f.read()
import subprocess
import shlex
# ✅ CORRECT - Safe command execution
def run_analysis(ticker: str) -> str:
# Validate input
if not ticker.isalpha():
raise ValueError("Invalid ticker")
# Use list form (safer)
result = subprocess.run(
["python", "analyze.py", ticker],
capture_output=True,
text=True,
timeout=30
)
return result.stdout
# ❌ WRONG - Command injection risk
def run_analysis(ticker: str) -> str:
result = subprocess.run(f"python analyze.py {ticker}", shell=True)
return result.stdout
# Check for known vulnerabilities
uv audit
# Update dependencies regularly
uv sync --upgrade
# ✅ CORRECT - Force HTTPS
import httpx
client = httpx.AsyncClient(
verify=True, # Verify SSL certificates
timeout=30.0
)
# ❌ WRONG - Insecure connection
client = httpx.AsyncClient(verify=False)
# Add security headers
headers = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains"
}
Before committing code:
| Security Concern | Solution |
|---|---|
| API keys | Environment variables + validation at startup |
| Sensitive logs | Mask keys (first 8 chars), anonymize financial data |
| Input validation | Pydantic v2 strict mode with extra='forbid' |
| Type safety | Full annotations, mypy strict mode |
| Rate limits | RateLimiter decorator, CrewAI max_rpm=20 |
| Timeouts | httpx.AsyncClient(timeout=30.0) |
| Error messages | Generic to users, detailed to logs |
| SQL injection | Parameterized queries |
| Path traversal | Path validation and resolution |
| Command injection | List form subprocess calls |
Apply these security standards consistently across all FinWiz development to protect sensitive financial data and maintain system integrity.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience