Skip to content

Commit 0de7bcc

Browse files
committed
random changes
1 parent e4c886f commit 0de7bcc

File tree

8 files changed

+401
-20
lines changed

8 files changed

+401
-20
lines changed

.gitignore

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,27 @@ coverage-report/
105105

106106
# Logs
107107
*.log
108+
logs/
109+
110+
# Local development files
111+
local_settings.py
112+
*.local.py
113+
*_local.py
114+
115+
# Database files
116+
*.db
117+
*.sqlite
118+
*.sqlite3
119+
120+
# Data files
121+
*.csv
122+
*.xlsx
123+
*.json
124+
*.pkl
125+
*.pickle
126+
*.h5
127+
*.hdf5
128+
129+
# Temporary files
130+
*.tmp
131+
*.temp

README.md

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,18 @@ A modern Python client for the Borsdata API, featuring:
1111

1212
## Installation
1313

14+
### From PyPI (Recommended)
15+
16+
```bash
17+
pip install borsdata-client
18+
```
19+
20+
### From Source
21+
1422
```bash
15-
pip install -r requirements.txt
23+
git clone https://github.com/yourusername/modern-borsdata-client.git
24+
cd modern-borsdata-client
25+
pip install -e .
1626
```
1727

1828
## Quick Start
@@ -30,23 +40,56 @@ with BorsdataClient(api_key) as client:
3040
# Get all instruments
3141
instruments = client.get_instruments()
3242

33-
# Get stock prices for an instrument
43+
# Get stock prices for a specific instrument
3444
today = datetime.now()
35-
last_month = today - timedelta(days=30)
36-
prices = client.get_stock_prices(
37-
instrument_id=3, # Example ID
38-
from_date=last_month,
45+
one_year_ago = today - timedelta(days=365)
46+
stock_prices = client.get_stock_prices(
47+
instrument_id=instruments[0].insId,
48+
from_date=one_year_ago,
3949
to_date=today
4050
)
4151

42-
# Get financial reports
43-
reports = client.get_reports(
44-
instrument_id=3,
45-
report_type="year",
46-
max_count=5
47-
)
52+
# Print the results
53+
print(f"Found {len(instruments)} instruments")
54+
print(f"Got {len(stock_prices)} price points for {instruments[0].name}")
55+
```
56+
57+
## Using in Your Projects
58+
59+
### As a Dependency
60+
61+
Add to your project's requirements.txt:
62+
63+
```
64+
borsdata-client>=0.1.0
65+
```
66+
67+
Or in your pyproject.toml:
68+
69+
```toml
70+
[project]
71+
dependencies = [
72+
"borsdata-client>=0.1.0",
73+
]
74+
```
75+
76+
### Environment Variables
77+
78+
For better security, you can store your API key in an environment variable:
4879

49-
# The client will automatically close the connection when exiting the context
80+
```python
81+
import os
82+
from borsdata_client import BorsdataClient
83+
from dotenv import load_dotenv
84+
85+
# Load environment variables from .env file
86+
load_dotenv()
87+
88+
# Get API key from environment
89+
api_key = os.getenv("BORSDATA_API_KEY")
90+
91+
# Initialize client
92+
client = BorsdataClient(api_key)
5093
```
5194

5295
## Documentation

examples/README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Borsdata Client Examples
2+
3+
This directory contains example scripts demonstrating how to use the Borsdata API client.
4+
5+
## Prerequisites
6+
7+
Before running these examples, make sure you have:
8+
9+
1. Installed the borsdata-client package:
10+
11+
```bash
12+
pip install borsdata-client
13+
```
14+
15+
2. Set up your API key as an environment variable or in a `.env` file:
16+
```
17+
BORSDATA_API_KEY=your_api_key_here
18+
```
19+
20+
## Examples
21+
22+
### Basic Usage (`basic_usage.py`)
23+
24+
A simple example showing how to fetch instruments, markets, and stock prices.
25+
26+
```bash
27+
python basic_usage.py
28+
```
29+
30+
### Portfolio Analysis (`portfolio_analysis.py`)
31+
32+
A more advanced example demonstrating how to analyze a portfolio of stocks.
33+
34+
**Additional Requirements:**
35+
36+
- pandas: `pip install pandas`
37+
38+
```bash
39+
python portfolio_analysis.py
40+
```
41+
42+
## Customizing the Examples
43+
44+
Feel free to modify these examples to suit your needs. You can:
45+
46+
- Change the portfolio stocks in `portfolio_analysis.py`
47+
- Adjust the time periods for historical data
48+
- Add additional analysis metrics
49+
- Integrate with visualization libraries like matplotlib or plotly

examples/basic_usage.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Basic usage example for the Borsdata API client.
4+
5+
This example demonstrates how to use the client to fetch basic data from the Borsdata API.
6+
"""
7+
8+
import os
9+
from datetime import datetime, timedelta
10+
from dotenv import load_dotenv
11+
from borsdata_client import BorsdataClient
12+
13+
# Load environment variables from .env file
14+
load_dotenv()
15+
16+
# Get API key from environment
17+
api_key = os.getenv("BORSDATA_API_KEY")
18+
if not api_key:
19+
raise ValueError("BORSDATA_API_KEY environment variable not set")
20+
21+
def main():
22+
"""Run the example."""
23+
# Use the client as a context manager
24+
with BorsdataClient(api_key) as client:
25+
# Get all instruments
26+
print("Fetching instruments...")
27+
instruments = client.get_instruments()
28+
print(f"Found {len(instruments)} instruments")
29+
30+
# Get markets
31+
print("\nFetching markets...")
32+
markets = client.get_markets()
33+
print(f"Found {len(markets)} markets:")
34+
for market in markets:
35+
print(f" - {market.name} (ID: {market.id})")
36+
37+
# Get stock prices for a specific instrument (using the first one as an example)
38+
if instruments:
39+
instrument = instruments[0]
40+
print(f"\nFetching stock prices for {instrument.name}...")
41+
42+
today = datetime.now()
43+
one_month_ago = today - timedelta(days=30)
44+
45+
prices = client.get_stock_prices(
46+
instrument_id=instrument.insId,
47+
from_date=one_month_ago,
48+
to_date=today
49+
)
50+
51+
print(f"Found {len(prices)} price points:")
52+
for i, price in enumerate(prices[:5]): # Show only first 5 prices
53+
print(f" - {price.d}: Close: {price.c}, Volume: {price.v}")
54+
55+
if len(prices) > 5:
56+
print(f" ... and {len(prices) - 5} more")
57+
58+
if __name__ == "__main__":
59+
main()

examples/portfolio_analysis.py

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Portfolio analysis example using the Borsdata API client.
4+
5+
This example demonstrates how to use the client to analyze a portfolio of stocks.
6+
"""
7+
8+
import os
9+
from datetime import datetime, timedelta
10+
from typing import Dict, List, Tuple
11+
import pandas as pd
12+
from dotenv import load_dotenv
13+
from borsdata_client import BorsdataClient, Instrument, StockPrice
14+
15+
# Load environment variables from .env file
16+
load_dotenv()
17+
18+
# Get API key from environment
19+
api_key = os.getenv("BORSDATA_API_KEY")
20+
if not api_key:
21+
raise ValueError("BORSDATA_API_KEY environment variable not set")
22+
23+
# Define a sample portfolio (ticker: number of shares)
24+
PORTFOLIO = {
25+
"ERIC B": 100, # Ericsson
26+
"VOLV B": 50, # Volvo
27+
"SEB A": 75, # SEB
28+
}
29+
30+
def get_instrument_by_ticker(client: BorsdataClient, ticker: str) -> Instrument:
31+
"""Find an instrument by its ticker symbol."""
32+
instruments = client.get_instruments()
33+
for instrument in instruments:
34+
if instrument.ticker == ticker:
35+
return instrument
36+
raise ValueError(f"Instrument with ticker {ticker} not found")
37+
38+
def get_historical_prices(
39+
client: BorsdataClient,
40+
instrument_id: int,
41+
days: int = 365
42+
) -> List[StockPrice]:
43+
"""Get historical prices for an instrument."""
44+
today = datetime.now()
45+
start_date = today - timedelta(days=days)
46+
47+
return client.get_stock_prices(
48+
instrument_id=instrument_id,
49+
from_date=start_date,
50+
to_date=today
51+
)
52+
53+
def calculate_portfolio_value(
54+
client: BorsdataClient,
55+
portfolio: Dict[str, int]
56+
) -> Tuple[float, Dict[str, float], pd.DataFrame]:
57+
"""Calculate the current value of a portfolio and its performance."""
58+
total_value = 0.0
59+
stock_values = {}
60+
price_history = {}
61+
62+
# Get data for each stock in the portfolio
63+
for ticker, shares in portfolio.items():
64+
try:
65+
# Get the instrument
66+
instrument = get_instrument_by_ticker(client, ticker)
67+
68+
# Get historical prices
69+
prices = get_historical_prices(client, instrument.insId)
70+
71+
if not prices:
72+
print(f"No price data available for {ticker}")
73+
continue
74+
75+
# Get the latest price
76+
latest_price = prices[-1].c
77+
stock_value = latest_price * shares
78+
79+
# Store the results
80+
total_value += stock_value
81+
stock_values[ticker] = stock_value
82+
83+
# Create a time series of prices
84+
dates = [price.d for price in prices]
85+
close_prices = [price.c for price in prices]
86+
price_history[ticker] = pd.Series(close_prices, index=dates)
87+
88+
print(f"{ticker}: {shares} shares at {latest_price:.2f} = {stock_value:.2f}")
89+
90+
except ValueError as e:
91+
print(f"Error processing {ticker}: {e}")
92+
93+
# Create a DataFrame with all price histories
94+
df = pd.DataFrame(price_history)
95+
96+
# Calculate portfolio value over time (weighted by shares)
97+
portfolio_weights = {}
98+
for ticker, shares in portfolio.items():
99+
if ticker in df.columns:
100+
portfolio_weights[ticker] = shares
101+
102+
# Calculate weighted sum
103+
if portfolio_weights:
104+
df['Portfolio'] = sum(df[ticker] * shares for ticker, shares in portfolio_weights.items())
105+
106+
return total_value, stock_values, df
107+
108+
def main():
109+
"""Run the portfolio analysis example."""
110+
with BorsdataClient(api_key) as client:
111+
print("Analyzing portfolio...")
112+
total_value, stock_values, price_history = calculate_portfolio_value(client, PORTFOLIO)
113+
114+
print("\nPortfolio Summary:")
115+
print(f"Total Value: {total_value:.2f}")
116+
117+
print("\nAllocation:")
118+
for ticker, value in stock_values.items():
119+
percentage = (value / total_value) * 100 if total_value > 0 else 0
120+
print(f" {ticker}: {value:.2f} ({percentage:.2f}%)")
121+
122+
# Calculate performance metrics if we have data
123+
if not price_history.empty and 'Portfolio' in price_history.columns:
124+
portfolio_series = price_history['Portfolio']
125+
126+
# Calculate returns
127+
returns = portfolio_series.pct_change().dropna()
128+
129+
print("\nPerformance Metrics:")
130+
print(f" Start Value: {portfolio_series.iloc[0]:.2f}")
131+
print(f" End Value: {portfolio_series.iloc[-1]:.2f}")
132+
133+
total_return = (portfolio_series.iloc[-1] / portfolio_series.iloc[0] - 1) * 100
134+
print(f" Total Return: {total_return:.2f}%")
135+
136+
annualized_return = ((1 + total_return/100) ** (365/len(portfolio_series)) - 1) * 100
137+
print(f" Annualized Return: {annualized_return:.2f}%")
138+
139+
volatility = returns.std() * (252 ** 0.5) * 100 # Annualized volatility
140+
print(f" Volatility (Annualized): {volatility:.2f}%")
141+
142+
if volatility > 0:
143+
sharpe = annualized_return / volatility # Simplified Sharpe ratio (no risk-free rate)
144+
print(f" Sharpe Ratio: {sharpe:.2f}")
145+
146+
if __name__ == "__main__":
147+
main()

0 commit comments

Comments
 (0)