Update projects/forex_algo_trading.md
This commit is contained in:
@@ -53,65 +53,55 @@ swing_trading_project/
|
||||
- Save the data to `data/` as CSV.
|
||||
|
||||
```python
|
||||
import csv
|
||||
import os
|
||||
from oandapyV20 import API # The Oanda API wrapper
|
||||
import oandapyV20.endpoints.instruments as instruments
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from oandapyV20 import API
|
||||
import oandapyV20.endpoints.instruments as instruments
|
||||
|
||||
# Configuration
|
||||
ACCOUNT_ID = 'your_account_id_here'
|
||||
ACCESS_TOKEN = 'your_access_token_here'
|
||||
INSTRUMENT = 'EUR_USD'
|
||||
GRANULARITY = 'H4' # 4-hour candles
|
||||
OUTPUT_FILENAME = 'eur_usd_data.csv'
|
||||
|
||||
# Directory for saving the data
|
||||
INSTRUMENTS = ['EUR_USD', 'USD_JPY', 'GBP_USD', 'AUD_USD', 'USD_CAD'] # Extendable to more pairs
|
||||
GRANULARITY = 'H4' # Can be parameterized as needed
|
||||
DATA_DIR = 'data'
|
||||
if not os.path.exists(DATA_DIR):
|
||||
os.makedirs(DATA_DIR)
|
||||
|
||||
def fetch_data(account_id, access_token, instrument, granularity):
|
||||
"""Fetch historical forex data for a specified instrument and granularity."""
|
||||
def fetch_and_save_data(account_id, access_token, instruments, granularity, data_dir):
|
||||
"""Fetch historical forex data for specified instruments and save to CSV."""
|
||||
client = API(access_token=access_token)
|
||||
params = {
|
||||
"granularity": granularity,
|
||||
"count": 5000 # Maximum data points to fetch in one request
|
||||
}
|
||||
|
||||
# Create a data request
|
||||
data_request = instruments.InstrumentsCandles(instrument=instrument, params=params)
|
||||
data = client.request(data_request)
|
||||
if not os.path.exists(data_dir):
|
||||
os.makedirs(data_dir)
|
||||
|
||||
return data['candles']
|
||||
|
||||
def save_to_csv(data, filename):
|
||||
"""Save fetched forex data to a CSV file."""
|
||||
filepath = os.path.join(DATA_DIR, filename)
|
||||
with open(filepath, mode='w', newline='') as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(['Time', 'Open', 'High', 'Low', 'Close', 'Volume'])
|
||||
for instrument in instruments:
|
||||
params = {
|
||||
"granularity": granularity,
|
||||
"count": 5000 # Adjust based on needs
|
||||
}
|
||||
|
||||
for candle in data:
|
||||
writer.writerow([
|
||||
candle['time'],
|
||||
candle['mid']['o'],
|
||||
candle['mid']['h'],
|
||||
candle['mid']['l'],
|
||||
candle['mid']['c'],
|
||||
candle['volume']
|
||||
])
|
||||
data_request = instruments.InstrumentsCandles(instrument=instrument, params=params)
|
||||
data = client.request(data_request)
|
||||
candles = data.get('candles', [])
|
||||
|
||||
if candles:
|
||||
df = pd.DataFrame([{
|
||||
'Time': candle['time'],
|
||||
'Open': float(candle['mid']['o']),
|
||||
'High': float(candle['mid']['h']),
|
||||
'Low': float(candle['mid']['l']),
|
||||
'Close': float(candle['mid']['c']),
|
||||
'Volume': candle['volume']
|
||||
} for candle in candles])
|
||||
|
||||
# Save to CSV
|
||||
output_filename = f"{instrument.lower()}_data.csv"
|
||||
df.to_csv(os.path.join(data_dir, output_filename), index=False)
|
||||
print(f"Data saved for {instrument} to {output_filename}")
|
||||
|
||||
def main():
|
||||
"""Main function to fetch and save EUR/USD data."""
|
||||
print("Fetching data...")
|
||||
data = fetch_data(ACCOUNT_ID, ACCESS_TOKEN, INSTRUMENT, GRANULARITY)
|
||||
print(f"Fetched {len(data)} data points.")
|
||||
|
||||
print("Saving to CSV...")
|
||||
save_to_csv(data, OUTPUT_FILENAME)
|
||||
print(f"Data saved to {os.path.join(DATA_DIR, OUTPUT_FILENAME)}")
|
||||
"""Main function to orchestrate data fetching and saving."""
|
||||
print("Fetching data for instruments...")
|
||||
fetch_and_save_data(ACCOUNT_ID, ACCESS_TOKEN, INSTRUMENTS, GRANULARITY, DATA_DIR)
|
||||
print("Data fetching and saving complete.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user