# Convert dictionary to DataFrame df = pd.DataFrame(data) print(f"Financial Data DataFrame:\n{df}")
# Add date index df['Date'] = pd.date_range(start='2024-01-01', periods=3) df.set_index('Date', inplace=True) print(f"DataFrame with date index:\n{df}")
Code Example 2: Calculating Rolling Window Mean
1 2 3 4 5 6 7 8 9 10 11 12 13
import pandas as pd
# Create price data data = {'Price': [100, 102, 101, 105, 108, 106, 107]} df = pd.DataFrame(data)
# Calculate 3-day rolling mean df['3-day MA'] = df['Price'].rolling(window=3).mean() print(f"3-day rolling mean:\n{df}")
# Calculate 5-day rolling mean df['5-day MA'] = df['Price'].rolling(window=5).mean() print(f"5-day rolling mean:\n{df}")
3. Matplotlib
Our "secret weapon" for drawing charts that transforms boring data into gorgeous visualizations, making analysis results crystal clear.
Code Example 1: Plotting Price Time Series
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import matplotlib.pyplot as plt
# Stock price data prices = [100, 102, 101, 105, 108, 106, 107, 109, 112, 110] dates = list(range(1, 11)) # Simple date index
# Plot price time series plt.plot(dates, prices, marker='o', linestyle='-', color='b', label='Stock Price') plt.title('Stock Price Trend') plt.xlabel('Date') plt.ylabel('Price') plt.grid(True) plt.legend() plt.show()
Code Example 2: Plotting Bar Chart
1 2 3 4 5 6 7 8 9 10 11 12 13
import matplotlib.pyplot as plt
# Data categories and values categories = ['Stocks', 'Bonds', 'Gold', 'Forex'] values = [10, 15, 7, 12]
The "ultimate weapon" for technical analysis with all kinds of technical indicators available. It's so satisfying to use.
Code Example 1: Calculating RSI (Relative Strength Index)
1 2 3 4 5 6 7 8 9 10 11
import talib as ta import numpy as np
# Generate random price data np.random.seed(42) prices = np.random.random(100) * 100# Generate 100 random prices, range 0-100 print(f"Random price data:\n{prices}")
# Generate random price data np.random.seed(42) prices = np.random.random(100) * 100# Generate 100 random prices, range 0-100
# Calculate Simple Moving Average (SMA) sma = ta.SMA(prices, timeperiod=10) print(f"Simple Moving Average:\n{sma}")
# Calculate Exponential Moving Average (EMA) ema = ta.EMA(prices, timeperiod=10) print(f"Exponential Moving Average:\n{ema}")
5. Zipline
The "professional" for backtesting that lets you easily simulate trading strategies to see if they actually work.
Code Example 1: Simple Buy Strategy
from zipline import run_algorithm
from zipline.api import order, symbol
# Initialize function
def initialize(context):
context.asset = symbol('AAPL') # Set target stock to Apple
# Daily handle function
def handle_data(context, data):
## 🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 **AI 编程实战课** 帮你从零上手!
- 👉 **课程报名**:[点击这里报名,前3讲免费试听](https://r7up9.xetslk.com/s/1uP5YW)
- 👉 **免费试看**:[B站免费试看前3讲,先看看适不适合自己](https://www.bilibili.com/cheese/play/ss982042944)