Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto_candles is giving data of wrong length and dates #55

Open
AndrewBworth opened this issue Sep 8, 2023 · 1 comment
Open

crypto_candles is giving data of wrong length and dates #55

AndrewBworth opened this issue Sep 8, 2023 · 1 comment

Comments

@AndrewBworth
Copy link

Hello, I just started working with finnhub moving from yfinance. It's returning the wrong data, the data I ask for is today and up to 200 days back, but instead I get odd numbers like 128 days back or 228 days back, and the start and end times are completely wrong. Here's my "hello world", it has a unfinished function in the middle (functionmovingaverage), but it's just a rough unfinished program. I have a long list of crpytocurrencies reading out of a text file (CryptoList.txt)

#!/usr/bin/python

import finnhub
import pandas as pd
import datetime
import time

starttime = datetime.datetime.now() - datetime.timedelta(days = 200)
currenttime = datetime.datetime.now() - datetime.timedelta()
starttimestamp = int(starttime.timestamp())
currenttimestamp = int(currenttime.timestamp())

print(starttimestamp)
print(currenttimestamp)
cryptolist = open("CryptoList.txt")

fc = finnhub.Client(api_key="cjsjv99r01qm5ielfq1gcjsjv99r01qm5ielfq20")

def functionmovingaverage(pandasdata):
count = 199
sum200 = 0
sum50 = 0
sum20 = 0
sum10 = 0
sum5 = 0
lastval = 0
datalength = len(pandasdata)
print(datalength)
if datalength > 200:
print(datalength)
if datalength < 200:
return -333
for k in pandasdata.itertuples():
print(k)

for i in cryptolist.readlines():
fixedi = i.split('\n')[0]
name = fixedi
print(name)
res = fc.crypto_candles(name, 'D', starttimestamp, currenttimestamp)
dataframe = pd.DataFrame(res)
functionmovingaverage(dataframe)
time.sleep(1)

@canstralian
Copy link

import finnhub # Import the Finnhub API client
import pandas as pd
import datetime
import time

def get_valid_crypto_symbols(file_path):
"""Reads cryptocurrency symbols from a file and returns a list of valid symbols."""
valid_symbols = []
with open(file_path, 'r') as file:
for line in file:
symbol = line.strip() # Remove leading/trailing whitespaces
if symbol:
valid_symbols.append(symbol)
return valid_symbols

def fetch_crypto_data(client, symbol, start_timestamp, end_timestamp):
"""
Fetches cryptocurrency data for the given symbol within the specified time range.
Returns a pandas DataFrame containing the fetched data.
"""
try:
# Call Finnhub API to get cryptocurrency candles data
res = client.crypto_candles(symbol, 'D', start_timestamp, end_timestamp)
if 's' in res:
return pd.DataFrame(res['s']) # Convert the response to a DataFrame
else:
print(f"No data found for symbol {symbol}")
return None
except Exception as e:
print(f"Error fetching data for symbol {symbol}: {e}")
return None

def main():
# Define time range
start_time = datetime.datetime.now() - datetime.timedelta(days=200)
end_time = datetime.datetime.now()
start_timestamp = int(start_time.timestamp())
end_timestamp = int(end_time.timestamp())

# Initialize Finnhub client
api_key = "YOUR_API_KEY"  # Replace "YOUR_API_KEY" with your actual API key
client = finnhub.Client(api_key=api_key)

# Get valid cryptocurrency symbols from the file
crypto_symbols = get_valid_crypto_symbols("CryptoList.txt")

# Fetch data for each cryptocurrency symbol
for symbol in crypto_symbols:
    # Fetch data for the symbol
    crypto_data = fetch_crypto_data(client, symbol, start_timestamp, end_timestamp)
    if crypto_data is not None:
        # Process the fetched data or call other functions here
        print(f"Fetched data for {symbol}:")
        print(crypto_data.head())  # Just printing the first few rows for demonstration
        print()

    time.sleep(1)  # Add a delay to avoid hitting API rate limits

if name == "main":
main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants